Ask A Question


You’re not receiving notifications from this thread.

Update an attribute on belongs_to

Alan Reid asked in Rails
Hi all,
I have my products and groups set up like so...

class Product < ApplicationRecord
  has_many :product_groups
  has_many :groups, through: :product_groups

class Group < ApplicationRecord
  has_many :product_groups
  has_many :products, through: :product_groups

class ProductGroup < ApplicationRecord
  belongs_to :product
  belongs_to :group

Basically, a product belongs to a group. All seems to work well.

Now I have a form which is updating the product attributes perfectly well. However, how would I go about updating the group the product is in? I have tried to Google this, but there doesn't seem to be anything which helps.

All help would be much appreciated, thanks.

Hey Alan,

You kind of have two options:

1. Having nested fields for the product_groups. Primarily this would be just letting you add / remove these and then have a select box to choose which group. The gem cocoon would be good for this.
2. Having nested fields for the groups. This skips the product_group and the join association would be automatically created for you. This you could use checkboxes or a multi-select, but it wouldn't let you define other fields on the join table (if you needed to do that). It is a lot simpler though.
I think the second option maybe quickest, for now, I can always go back and refactor the code to improve it later.  At present, I just need to be able to assign a `produduct_group` to a product and let it be updated when editing the product.

How would I go about doing this?
Ok i seemed to have got it to work as i wanted, thanks for the guidance Chris :D
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,038+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.