2011-04-23 19 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之间的冲突。

相关问题