私はポリモーフィックな関連性を持っています:
class User
has_many :products
has_many :subscriptions, :foreign_key => :subscriber_id
end
class Product
belongs_to :store
has_many :subscriptions, :as => :subscribable
end
class Subscription
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
end
複製したいので、モデルは列を保持Subscription
します。Product
create_table :products do |t|
t.string :name
t.decimal :price
t.integer :user_id
t.integer :store_id
end
create_table :subscriptions do |t|
t.string :name
t.decimal :price
t.integer :store_id
t.integer :subscriber_id # user_id
t.integer :subscribable_id
t.string :subscribable_type
end
リンクで製品を購読しようとすると、次のようになります。
<td><%= link_to "Subscribe", { :controller => "products", :action => "subscribe_product", :id => product.id }, :method => :post %></td>
エラーが発生します:
NameError in ProductsController#subscribe_product
undefined local variable or method `store_id' for #<ProductsController:0x705bad8>
コントローラが製品フィールドを複製しようとしているため、次のようになります。
def subscribe_product
@product = Product.find(params[:id])
subscription = Subscription.new(@product.attributes.merge({
:store_id => store_id,
:price => price,
:name => name
}))
subscription.subscriber_id = current_user.id
@product.subscriptions << subscription
if @product.save
redirect_to :back, :notice => "Successfully subscribed to #{@product.name}"
else
render :back, :notice => "Could Not Subscribe to Product correctly."
end
end
誰かがこれを修正する方法を知っていますか?理由がわかりません。store_id
複製される残りのフィールドがNameError
?