Activerecord Find_Or_Build_By

ActiveRecord find_or_build_by

How about this?

employee_attrs = {:name => 'foo', :city => 'bar'}
e = c.employees.where(employee_attrs).first || c.employees.build(employee_attrs)

Rails - find or create - is there a find or build?

Try XXX.find_or_initialize_by_uuid(XXXX)

Rails: find_or_create_by equivalent that will not persist until save

You seem to be looking for #find_or_initialize_by. Instead of calling create, the named method calls new. To save the object (assuming it is initialized, and not found), you will call save as you want.

And if you look at the source code for the method, it does exactly what you are looking for!

def find_or_initialize_by(attributes, &block)
find_by(attributes) || new(attributes, &block)
end

On the docs page I provided with the method link, I was not able to find a bang (!) version of the method. Using the bang will raise an error. Depending on your use, you may not need it at all.

ruby when we are passing more than 4 value in set how it arrange that value in set

You've said "in language nothing is generated without order" but that isn't true. Hashes are generated without order.

In Ruby 1.9, though, additional infrastructure has been added on top of hashes to give them an insertion order that is used when iterating (meaning that even though they are stored unordered, they essentially maintain a linked list they can use when being traversed). Since sets are implemented with hashes, they will be unordered in 1.8 and ordered in 1.9, but you should not rely on this order (otherwise it's not a set, it's a list -- array in Ruby speak).

Here is a simple example of implementing a hash.

This article discusses how the ordering is added.

Rails: Using build with a has_one association in rails

The build method signature is different for has_one and has_many associations.

class User < ActiveRecord::Base
has_one :profile
has_many :messages
end

The build syntax for has_many association:

user.messages.build

The build syntax for has_one association:

user.build_profile  # this will work

user.profile.build # this will throw error

Read the has_one association documentation for more details.



Related Topics



Leave a reply



Submit