Coderama
Coderama

Reputation: 11362

How to delete an object of a has_many where the parent object is not yet saved

I have an @activity that has_many :clientships

When creating a new object I assign several Clientship objects but before saving, the user wants to pick out a few to delete.

How would I delete one of the following Clientship objects based on a user-defined client_id?

The collection looks like this:

@activity.clientships [
  #<Clientship id: nil, client_id: 1770>,
  #<Clientship id: nil, client_id: 24>,
  #<Clientship id: nil, client_id: 25>,
  #<Clientship id: nil, client_id: 2181,>
]

The example code I tried which didn't work (not to mention inefficient):

@activity.clientships.map {|o| o.delete if o.client_id==24 }

Upvotes: 2

Views: 1434

Answers (1)

Eimantas
Eimantas

Reputation: 49354

@activity.clienships.delete_if{|o| o.client_id == 24}

Upvotes: 2

Related Questions