2011-04-23 39 views
0

我在用戶和micropost之間有一個簡單的一對多關係,如下所示。我試圖在Micropost模型中添加一個名爲stage的新列。當我嘗試構建新的Micropost並保存時,stage列總是自動設置爲nil。我已嘗試create,build - 無所謂,stage字段始終設置爲nil。我很困惑,請幫忙!通過構建創建一個新的關聯對象總是將一些列設置爲零在Rails中

$ rails console 
Loading development environment (Rails 3.0.5) 
>> User.first.microposts.create!(:stage => "p", :content => "test 6") 

=> #<Micropost id: 2, content: "test 6", stage: nil, user_id: 1, created_at: "2011-04-23 22:14:20", updated_at: "2011-04-23 22:14:20"> 

...

class Micropost < ActiveRecord::Base 
    attr_accessible :content, :stage 
    attr_accessor :stage 

    belongs_to :user 

    validates :content, :presence => true, :length => { :maximum => 140 } 
    validates :user_id, :presence => true 

    default_scope :order => 'microposts.created_at DESC' 
    scope :from_users_followed_by, lambda { |user| followed_by(user) } 

    private 
    def self.followed_by(user) 
     followed_ids = %(SELECT followed_id FROM relationships 
         WHERE follower_id = :user_id) 
    where "user_id IN (#{followed_ids}) OR user_id = :user_id", 
             { :user_id => user } 
    end 

end 

...

class User < ActiveRecord::Base 
    attr_accessor :password 
    attr_accessible :name, :email, :password, :password_confirmation 

    has_many :microposts, :dependent => :destroy 
end 
+0

「stage」是數據庫中的真實列還是模型中的屬性? – ctcherry 2011-04-23 23:33:21

回答

0

您需要刪除行:

attr_accessor :stage 

沒有它,一切工作正常。我認爲這是attr_accessorattr_accessible之間的衝突。

相關問題