On Tuesday, March 11, 2014 3:13:24 AM UTC-7, Nicholas Wieland wrote:
>
> Hi, I'm loving sequel but having some difficulties handling associations.
> Say I have a blacklist object linked to many results, and I want to delete 
> the blacklist object nad put to nil all the Result.blacklist_id I have. I 
> did it this way:
>
>     result = Result[params[:id]]
>       result.blacklist.results.each do |r|
>         r.blacklist = nil
>         r.save
>       end
>       result.blacklist.destroy
>
> This code is pretty ugly and doesn't even work all that well. Does anybody 
> have any suggestion on how to improve it? I've read the docs and saw I 
> should have a remove_blacklist but I don't have it...
>

You haven't posted your association code, so I'm guessing you are doing:

  Result.many_to_one :blacklist
  Blacklist.one_to_many :results

If you want to delete a blacklist and set all of the blacklist_id fields in 
the associated results to nil:

  result =  Result[params[:id]]
  blacklist = result.blacklist
  blacklist.remove_all_results
  blacklist.destroy

The main problem with your code is that you are setting result.blacklist = 
nil in the each block, so by the time result.blacklist.destroy comes 
around, it result.blacklist should be nil.

You shouldn't have a remove_blacklist method if the association is 
many_to_one, that's only for *_many associations.

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to