I am developing a feature for creating specials, for a shopping website. One product can have more than one special, and obviously a special can have more than one product..
I am using a has_and_belongs_to_many
relationship, so i have declared:
Product.rb
has_and_belongs_to_many :specials
Special.rb
has_and belongs_to_many :products
Now, with a product @product
and a special @special
, an association is created like so..
@special.products << @product
After doing this, the following is true:
@special.products.first == @product
and, importantly:
@product.specials.first == @special
When i delete the association using this
@special.products.delete(@product)
then @product
is removed from specials, so @special.products.first==nil
, however @product
still contains @special
, in other words @products.specials.first==@special
Is there any proper way, apart from writing a delete method, to do this in a single call?
backticks
only work for strings - if you have blocks of code, you should indent by 4 spaces – Mueller@special
? – Foreordain@special.products.delete(@product)
actually does remove the association on both sides, as it deletes the record in the join table (ieproduct_specials
). Try@product.reload.specials
or telling.specials
to re-fetch the join table records by passing ittrue
, like so@product.specials(true)
. See here. – Mouthwatering'''ruby \n def myCode end \n '''
– Nunuance