views:

49

answers:

2

I have a venue model and i want to do this

Venue.find_or_create_by_

but i only want a new venue to be created if one with the same name and date do not already exist

For example

=> Venue(id: integer, location: string, showdate: datetime, created_at: datetime, updated_at: datetime)

A venue is unique and needs to be created if the location and the showdate are not present in the db

A: 
my_class = ClassName.find_or_initialize_by_showdate_and_location(showdate,location)
my_class.update_attributes!

find_or_initialize method find by name and location in database. If record doesn't exist than it initialize new record with showdate and location. http://api.rubyonrails.org/classes/ActiveRecord/Base.html This link will help you to figure out find_or_initialize and find_or_create.

krunal shah
Calling `.update_attributes!` without passing any attributes is pretty useless. `.save!` would be a much better option. And in this case, the requester has already said he wants to use `.find_or_create`, so you shouldn't have to initialize and save the record in two separate steps.
vonconrad
@vonconrad I have already provided link which give an idea about both the methods. Whatever user would like to use it. I was giving idea both methods are available.
krunal shah
+2  A: 

You can chain columns together by using _and_. This should do the trick:

Venue.find_or_create_by_location_and_showdate(location, showdate)
vonconrad