views:

90

answers:

2

Don't mind me, I fricked up my attribute names :(

This is entirely possible, using the exact syntax I used - you just need to be able to spell!


I can't seem to get this to work, and it seems like a common enough scenario that there must be a solution, but I'm not having any luck with the correct terminology to get a helpful Google result.

I want to do this:

u = User.first
u.clients.find_or_create_by_email('[email protected]')

With the effect that a new Client is created with user_id = u.id.

Can I get the nice dynamic finders through a has_many relationship? If not, why?

Thanks :)

A: 

This

u = User.first
u.clients.find_or_create_by_email('[email protected]')

works if you have has_many relationship set. However, it won't raise validation error if you have any validations set on your Client object and it will silently fail if the validation fails.

You can check the output in your console when you do

u.clients.find_or_create_by_email('[email protected]') # => #<Client id: nil, email: '[email protected]', name: nil, user_id: 1, another_attribute: nil, active: true, created_at: nil, updated_at: nil>

and the user_id will be set but not the id of client because the validation has failed and the client is not created

So this should create the client only if you pass all the required attributes of client object and the validation for client object has passed successfully.

So lets say your client model has validation on name as well apart from email then you should do

u.clients.find_or_create_by_email_and_name('[email protected]', 'my_name') #=> #<Client id: 1, email: '[email protected]', name: 'my_name', user_id: 1, another_attribute: nil, active: true, created_at: "2009-12-14 11:08:23", updated_at: "2009-12-14 11:08:23">
nas
A: 

This is entirely possible, using the exact syntax I used - you just need to be able to spell!

nfm