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 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
于 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はコントローラーメソッドのローカル変数ではなく、他の方法ではスコープ内にないため、コンピューターはそれらが何であるかを認識しません。(それらが何であるかはわかりません。これらの値はどこから来るのでしょうか?)

Productまた、との間の列を複製している理由もわかりませんSubscription。これは、データの不要な重複ではないようです。あなたはそれをすることによって何を達成しようとしていますか?

于 2012-04-07T04:02:35.480 に答える