更新模型中具有多对多关系的属性

时间:2012-06-24 22:44:23

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有两个具有多对多关联的模型(一个事件有很多产品和产品有很多事件),我正在尝试将一个产品添加到一个事件中。我使用单表继承来实现系统需要处理的许多类型的产品,这就是为什么在Lighting下面的错误是模型名称而不是产品。 我在控制器中使用以下方法将产品添加到事件中,但是会发生以下错误:

NoMethodError in AddeventController#add

undefined method `each' for #<Lighting:0x007fd4bc798c70>

app/controllers/addevent_controller.rb:5:in `add'

我的行动看起来像:

  def add
      @event = current_event
      product = Product.find(params[:id])
      if @event.update_attribute(:products, product) #This is line 5
        format.html {redirect_to @event, notice: "Product added to event"}
      end
    end

Current_event只是一种从会话中提取事件id的方法。

所以出了什么问题?

1 个答案:

答案 0 :(得分:3)

您可能需要将产品包装在一个数组中,因为很多关系都适用于数组。

@event.update_attribute(:products, [product])

此外,操作的名称表明您希望在事件中添加产品,而不仅仅是使用单个产品替换事件的产品。也许你应该这样做:

@event.products << product