Ruby on rails 3 元素的多态关联,还需要添加其他内容吗?
我已经接受了,但我不确定为什么有些东西不起作用 我有一个pricable多态关联,我只用于一个名为Item的模型。看起来是这样的:Ruby on rails 3 元素的多态关联,还需要添加其他内容吗?,ruby-on-rails-3,activerecord,Ruby On Rails 3,Activerecord,我已经接受了,但我不确定为什么有些东西不起作用 我有一个pricable多态关联,我只用于一个名为Item的模型。看起来是这样的: class Item < ActiveRecord::Base #price has_one :price, :as => :pricable accepts_nested_attributes_for :price attr_accessible :price_attributes, :price, .... 嗯。。。。看起来关系设
class Item < ActiveRecord::Base
#price
has_one :price, :as => :pricable
accepts_nested_attributes_for :price
attr_accessible :price_attributes, :price, ....
嗯。。。。看起来关系设置正确,该事件可以通过attr_accessible访问price。你知道还会发生什么吗
thx关系似乎定义正确,但如果e.price返回nil,则显然e.price.price=将不起作用,并返回未定义的方法错误。您需要首先构建/创建关联的price对象:
> e = Event.find(19)
=> #<Event id: 19, ...>
> e.price
=> nil
> e.create_price(price: 23)
=> #<Price id: 1, priceable_id: 19, price: 23, ...>
>e=Event.find(19)
=> #
>e.价格
=>零
>e.创建价格(价格:23)
=> #
或者,如果要使用嵌套属性:
> e = Event.find(19)
=> #<Event id: 19, ...>
> e.price
=> nil
> e.update_attributes(price_attributes: { price: 23 })
=> true
> e.price
=> #<Price id: 1, priceable_id: 19, price: 23, ...>
>e=Event.find(19)
=> #
>e.价格
=>零
>更新属性(价格属性:{price:23})
=>正确
>e.价格
=> #
这就是您的模型的外观
class Price < ActiveRecord::Base
attr_accessible :value
belongs_to :priceable, :polymorphic => true
end
class Item < ActiveRecord::Base
attr_accessible :name, :price_attributes
has_one :price, :as => :priceable
accepts_nested_attributes_for :price
end
class Event < ActiveRecord::Base
attr_accessible :name, :price_attributes
has_one :price, :as => :priceable
accepts_nested_attributes_for :price
end
class CreatePictures < ActiveRecord::Migration
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
end
end
酷,build\u price是create\u price的别名吗?我在赏金后5分钟就可以开始工作了。哈哈…build\u price不是create\u price的别名。它们之间的区别在于,build\u price只生成关联的price对象,不将其保存到数据库中,而create\u price生成price对象并立即保存。查看文档以了解有关生成关联和创建关联方法的详细信息。
class Price < ActiveRecord::Base
attr_accessible :value
belongs_to :priceable, :polymorphic => true
end
class Item < ActiveRecord::Base
attr_accessible :name, :price_attributes
has_one :price, :as => :priceable
accepts_nested_attributes_for :price
end
class Event < ActiveRecord::Base
attr_accessible :name, :price_attributes
has_one :price, :as => :priceable
accepts_nested_attributes_for :price
end
class CreatePictures < ActiveRecord::Migration
def change
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
end
end
Item.new( { name: 'John', price_attributes: { value: 80 } } )