【问题标题】:Update attribute in model with many to many relationship更新具有多对多关系的模型中的属性
【发布时间】:2012-06-25 06:49:36
【问题描述】:

我有 2 个具有多对多关联的模型(一个活动有很多产品,而产品有很多活动),我正在尝试将一个产品添加到一个活动中。我已经使用单表继承来实现系统需要处理的多种类型的产品,这就是为什么下面的错误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 的方法。

那么怎么了?

【问题讨论】:

  • 每个用于照明,但我看不到照明。这可能就是您的问题所在。
  • 你应该把代码贴在这个 .each 被调用的地方——不能诊断出我们看不到的东西
  • @Trip 查看我对此的编辑。
  • @Rabbott 我不知道 .each 在哪里被调用,因为我没有这样做。
  • 发布您的 addevent_controller.rb

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


【解决方案1】:

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

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

此外,操作的名称表明您希望在活动中添加产品,而不仅仅是将活动的产品替换为单个产品。所以你应该这样做:

@event.products << product

【讨论】:

  • 感谢并感谢您发现未来更换所有产品的错误,而不仅仅是添加一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
  • 2014-05-16
  • 2023-01-31
相关资源
最近更新 更多