Активная модель Вставка значений NULL в новые и создание вызовов методов - PullRequest
0 голосов
/ 30 января 2012

Это мой дамп вебрика при вызове метода create_note для модели note

Parameters: {"utf8"=>"✓", "authenticity_token"=>"T/F/oZaUYHz7G3HUjVKDs+Qjx+hrg6VqU4t1vr14ACc=", "note"=>{"notename"=>"Hello World 3", "notecontent"=>"3rd time hello world"}, "commit"=>"Create"}
   (0.2ms)  BEGIN
  SQL (0.3ms)  INSERT INTO `notes` (`created_at`, `notecontent`, `notename`, `updated_at`, `user_id`) VALUES ('2012-01-30 07:04:31', NULL, NULL, '2012-01-30 07:04:31', 1)
   (3.3ms)  COMMIT
   (0.1ms)  BEGIN
   (0.1ms)  COMMIT
  Rendered note/create.html.erb within layouts/application (2.5ms)
Completed 200 OK in 58ms (Views: 13.4ms | ActiveRecord: 5.8ms)

Смотрите, что вставка идет со значениями NULL для notecontent и notename.

Файл моей модели

class Note < ActiveRecord::Base
        self.table_name = "notes"
        validates_length_of :notename, :within => 5..50, :message => "Notename 5-50 chars"
        validates_length_of :notecontent, :within => 5..50, :message => "Notecontent 5-50 chars"
        attr_protected :id
        belongs_to :user

        attr_accessor :notename, :notecontent, :created_at, :updated_at

        def self.get_notes_by_user(id)
                usernotes =  Note.find :all, :conditions => ["user_id = ?", id]
                return usernotes
        end


        def self.create_note(name, content, user)
                n = Note.create(:notename => name , :notecontent => content, :user_id => user)
                if n.save!
                        return true
                else
                        return false
                end
        end

        def self.update_note (id, content)
                n = Note.find :first, :conditions => ["id = ?", id]
                n.notecontent = content;
                n.updated_at = 0.hour.from_now
        end
end

Файл моего контроллера

class NoteController < ApplicationController

        #before_filter :login_required
  def create
        if session[:user] == nil
                redirect_to :controller => "user", :action => "login"
        end
        if request.post?
                @nname = params[:note][:notename]
                @ncontent = params[:note][:notecontent]
                @uid = session[:user].getid
                @ins = params.inspect
                status = Note.create_note @nname, @ncontent, @uid
                if status == false
                        flash[:warning] = "Error While Creating Note"
                else
                        flash[:notice] =  "Note Successfully Created"
                end
        end
  end

  def delete
  end

  def show
  end

  def index
        if session[:user] == nil
                redirect_to :controller => "user", :action => "login"
        end
        user = session[:user]
        @uname = user.getname
        #nn = Note.new
        @user_notes =  Note.get_notes_by_user(user.getid)
  end
end

Я проверил, что значения заполняются для аргументов в методе create_note в модели заметок. но, похоже, что-то не получается отобразить эти значения на язык запросов к базе данных. Пожалуйста, помогите.

Файл моей миграции

class AddUidToNotes < ActiveRecord::Migration
  def self.up
        add_column :notes, :user_id, :int
  end
end

class CreateNotes < ActiveRecord::Migration
  def self.up
    create_table :notes do |t|
        t.column :notename, :string
        t.column :notecontent, :string
      t.timestamps
    end
  end

  def self.down
    drop_table :notes
  end
end

DBCONSOLE

mysql> desc notes;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| notename    | varchar(255) | YES  |     | NULL    |                |
| notecontent | varchar(255) | YES  |     | NULL    |                |
| created_at  | datetime     | NO   |     | NULL    |                |
| updated_at  | datetime     | NO   |     | NULL    |                |
| user_id     | int(11)      | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

1 Ответ

2 голосов
/ 30 января 2012

Никогда не используйте attr_accessor с атрибутом базы данных.Это переопределит средства доступа, которые ActiveRecord предоставляет с отдельным набором средств доступа, которые не записывают в хранилище, которое использует ActiveRecord.

Не следует путать с attr_accessible, который является частью системы защиты массовых назначений и абсолютно хорошоиспользовать

...