Reputation: 8978
I have 2 models that have a many-to-many association(an Event has many Products and Products have many events), and I am trying to add one product to an event. I have used single table inheritance to implement the many types of products that the system needs to handle, this is why in the error below Lighting
is the model name not products.
I have the following method in my controller to add the product to the event, however the following error occurs:
NoMethodError in AddeventController#add
undefined method `each' for #<Lighting:0x007fd4bc798c70>
app/controllers/addevent_controller.rb:5:in `add'
And my action looks like:
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 is just a method that pulls the id of the event from the session.
So whats going wrong?
Upvotes: 0
Views: 277
Reputation: 10907
You might need to wrap the product in an array, as many to many relations work on arrays.
@event.update_attribute(:products, [product])
Also, the name of the action suggests that you want to add the product in the event and not just replace the event's products with the single product. so may be you should do:
@event.products << product
Upvotes: 3