开发者

Can I scope dynamic attribute-based finders to an object?

开发者 https://www.devze.com 2022-12-14 02:52 出处:网络
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 ab开发者_高级运维le to spell!

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 ab开发者_高级运维le 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('example@example.com')

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 :)


This

u = User.first
u.clients.find_or_create_by_email('example@example.com')

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('example@example.com') # => #<Client id: nil, email: 'example@example.com', 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('example@example.com', 'my_name') #=> #<Client id: 1, email: 'example@example.com', 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">


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

0

精彩评论

暂无评论...
验证码 换一张
取 消