我有多态关联:
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
?
答案 0 :(得分:1)
使用实例变量@product get store_id,price和name的值,如下所示:
def subscribe_product
@product = Product.find(params[:id])
subscription = Subscription.new(
:store_id => @product.store_id,
:price => @product.price,
:name => @product.name
)
subscription.subscriber = current_user
@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
答案 1 :(得分:0)
您获得的错误是因为控制器中的这一行:
subscription = Subscription.new(@product.attributes.merge({
:store_id => store_id,
:price => price,
:name => name
}))
store_id
,price
和name
不是控制器方法中的局部变量,并且不在任何其他方式的范围内,因此计算机不知道什么他们应该是。 (我不确定它们应该是什么;这些值应该来自哪里?)
我也不明白为什么要复制Product
和Subscription
之间的列。这似乎是不必要的重复数据。你想通过这样做实现什么目标?