Update an attribute on belongs_to
Hi all,
I have my products and groups set up like so...
I have my products and groups set up like so...
class Product < ApplicationRecord has_many :product_groups has_many :groups, through: :product_groups end
class Group < ApplicationRecord has_many :product_groups has_many :products, through: :product_groups end
class ProductGroup < ApplicationRecord belongs_to :product belongs_to :group end
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.
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?
How would I go about doing this?