在Rails中,通过构建创建一个新的关联对象总是将一些列设置为nil



我在用户和微博之间有一个简单的一对多关系,如下所示。我尝试在Micropost模型中添加一个名为stage的新专栏。当我尝试建立一个新的微博并保存时,stage列总是自动设置为nil。我试过create, build -没关系,stage字段总是设置为nil。我很困惑,请帮忙!

$ 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

你需要删除line:

attr_accessor :stage

没有它一切都很好。我认为这是attr_accessorattr_accessible之间的冲突。

相关内容

  • 没有找到相关文章

最新更新