0

我有一个多态关联:

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?

4

2 回答 2

1

使用实例变量@product 获取 store_id、价格和名称的值,如下所示:

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
于 2012-04-07T04:29:01.853 回答
0

你得到的错误是因为你的控制器中的这一行:

subscription = Subscription.new(@product.attributes.merge({
  :store_id => store_id,
  :price => price,
  :name => name
}))

store_id, price, 并且name不是控制器方法中的局部变量,并且不在任何其他方式的范围内,因此计算机不知道它们应该是什么。(我也不确定它们应该是什么;这些值应该来自哪里?)

我也不明白你为什么要复制 和 之间的ProductSubscription。这似乎是不必要的数据重复。你想通过这样做来达到什么目的?

于 2012-04-07T04:02:35.480 回答