1

私は採用しましたが、何かが機能していない理由が正確にはわかりません。

Item と呼ばれる 1 つのモデルのみに使用する高価なポリモーフィック アソシエーションがあります。次のようになります。

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

  attr_accessible :price_attributes, :price, ....

Event モデルに追加したいのですが、以下を追加しました。

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 を介して価格にアクセスできます。他に何が起こっているのでしょうか?

どうも

4

2 に答える 2

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, ...>
于 2012-07-16T22:34:14.773 に答える
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 } } )
于 2012-07-17T05:45:48.937 に答える