Rails find or create based on two fields
I hav开发者_开发问答e 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
You can chain columns together by using _and_
. This should do the trick:
Venue.find_or_create_by_location_and_showdate(location, showdate)
In rails 4 you would do:
Venue.find_or_create_by(location: location, showdate: showdate)
Much prettier, if you ask me!
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.
精彩评论