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
场地是唯一的,如果db中没有位置和showdate,则需要创建场地
3 个解决方案
#1
42
You can chain columns together by using _and_
. This should do the trick:
您可以使用_and_将列链接在一起。这应该是诀窍:
Venue.find_or_create_by_location_and_showdate(location, showdate)
#2
7
In rails 4 you would do:
在rails 4中你会做:
Venue.find_or_create_by(location: location, showdate: showdate)
Much prettier, if you ask me!
如果你问我,那就更漂亮了!
#3
1
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.
find_or_initialize方法按名称和数据库中的位置查找。如果记录不存在,则使用showdate和location初始化新记录。 http://api.rubyonrails.org/classes/ActiveRecord/Base.html此链接将帮助您找出find_or_initialize和find_or_create。
#1
42
You can chain columns together by using _and_
. This should do the trick:
您可以使用_and_将列链接在一起。这应该是诀窍:
Venue.find_or_create_by_location_and_showdate(location, showdate)
#2
7
In rails 4 you would do:
在rails 4中你会做:
Venue.find_or_create_by(location: location, showdate: showdate)
Much prettier, if you ask me!
如果你问我,那就更漂亮了!
#3
1
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.
find_or_initialize方法按名称和数据库中的位置查找。如果记录不存在,则使用showdate和location初始化新记录。 http://api.rubyonrails.org/classes/ActiveRecord/Base.html此链接将帮助您找出find_or_initialize和find_or_create。