【发布时间】:2011-01-02 16:27:44
【问题描述】:
我想使用accepts_nested_attributes_for 创建一个has_many Sections 的Article 对象。
class Article < ActiveRecord::Base
has_many :sections, :order => "position", :dependent => :destroy
belongs_to :categories
accepts_nested_attributes_for :sections, :allow_destroy => true, :reject_if => lambda { |attributes| attributes['title'].blank? }
validates_presence_of :name, :on => :create, :message => "An article must have a title"
end
class Section < ActiveRecord::Base
belongs_to :article
acts_as_list :scope => "article"
has_attached_file :image,
:styles => { :medium => "300x300>",
:thumb => "100x100>" }
end
只要:reject_if 条件接受嵌套属性(如果title 属性不是blank?),我就会看到SQLException。否则,将成功创建文章而没有关联的部分。
Parameters: {"article"=>{"name"=>"My Article", "category_id"=>"7", "sections_attributes"=>{"0"=>{"title"=>"Section 1", "content"=>"Section 1 of my new article"}}}}
AREL (30.3ms) INSERT INTO "articles" ("content", "category_id", "position", "name") VALUES (NULL, 7, NULL, 'My Article')
Section Load (0.4ms) SELECT "sections".* FROM "sections" WHERE (article) ORDER BY position DESC LIMIT 1
SQLite3::SQLException: no such column: article: SELECT "sections".* FROM "sections" WHERE (article) ORDER BY position DESC LIMIT 1
Completed in 68ms
我试图找出在Section Load 阶段出了什么问题,因为WHERE (article) 是出乎意料的。感谢阅读。
【问题讨论】:
-
值得注意的是:我遇到了与其他两个具有相同一对多关系的独立模型相同的问题。我正在使用 Rails 3.0.3
-
我假设模型关联可以从控制台找到?尝试从控制台嵌套属性,并尝试简化您的关联/accepts_nested 声明,KISS。
-
在控制台中运行
Article.create!({:name=>"Console Test", :sections_attributes=>[{:title=>"Section 1.1"}]})会导致相同的 SQLException。我尝试将 Accepts_nested 声明简化为最简单的形式,只指定嵌套模型名称。如问题所述,当:reject_if条件失败或根本未声明时,一切正常。该错误仅在接受嵌套对象时发生。
标签: ruby-on-rails-3 nested-attributes