2012-07-13 30 views
1

我已經採納了,我不確定爲什麼有些東西不起作用。元素的多態關聯,還有其他什麼需要添加?

我有一個pricable多態關聯,我只用於一個稱爲Item的單一模型。它看起來像這樣:

class Item < ActiveRecord::Base 
    #price 
    has_one :price, :as => :pricable 
    accepts_nested_attributes_for :price 

    attr_accessible :price_attributes, :price, .... 

我想添加到一個事件模型,並添加以下內容:

class Event < ActiveRecord::Base 
    #price 
    has_one :price, :as => :pricable 
    accepts_nested_attributes_for :price 
    attr_accessible :price, :price_attributes 

但是,我不能設置:

ruby-1.9.2-p290 :001 > e=Event.find(19) #ok 
ruby-1.9.2-p290 :002 > e.price 
Creating scope :page. Overwriting existing method Price.page. 
    Price Load (0.8ms) SELECT `prices`.* FROM `prices` WHERE `prices`.`pricable_id` = 19 AND `prices`.`pricable_type` = 'Event' LIMIT 1 
=> nil 
ruby-1.9.2-p290 :003 > e.price.price=23 
NoMethodError: undefined method `price=' for nil:NilClass 
    from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.0/lib/active_support/whiny_nil.rb:48:in `method_missing' 
    from (irb):3 

嗯....它看起來像關係設置正確,該事件可以通過attr_accessible訪問價格。任何想法還有什麼可以進行?

THX

回答

1

關係似乎正確定義,但是,如果然後e.price返回nil明顯e.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) 
=> #<Event id: 19, ...> 
> e.price 
=> nil 
> e.update_attributes(price_attributes: { price: 23 }) 
=> true 
> e.price 
=> #<Price id: 1, priceable_id: 19, price: 23, ...> 
+0

,是build_price爲create_price的別名?賞金後我能夠工作5分鐘。大聲笑... – timpone 2012-07-17 03:08:46

+0

build_price不是create_price的別名。它們之間的區別在於,build_price只構建關聯的價格對象,並且不將其保存到數據庫,而create_price構建價格對象並立即保存。有關build_association和create_association方法的詳細信息,請查看[has_one](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one)文檔。 – mdominiak 2012-07-17 06:58:56

1

這是你的模型看起來應該像

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 } }) 
相關問題