Skip to main content

Update an attribute on belongs_to

Rails • Asked by Alan Reid
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

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.