我想在rails中插入多个数据。我使用的是postgresql,场景是表单提交时传递客户名称,电子邮件和一些个人信息,然后还传递日期,想要的便利设施以及他们想要的便利设施(例如游泳民意测验,台球民意测验等)。 )。在我的后端,我将查询:
venue = Venue.find(theVenue_id)
book = venue.books.new(name: client_name, email: client_email and etc)
我的问题是,如果选择了许多便利设施,该如何在amenity_books中插入数据?
我尝试这样的事情。
ex. amenities_id_choosen = [1,3]
if book.save
amenities_id_choosen.each do |x|
amenity = Amenitiy.find(x)
amenity_book = amenity.amenity_books.create(venue_id: venue.id)
end
我知道插入数据不是一个好主意,但这是我的最后选择。有谁知道如何在具有不同数据的2个模型中插入多个数据。
楷模
class Amenity < ActiveRecord::Base
has_many :categorizations
has_many :venues, through: :categorizations
has_many :amenity_books
has_many :books, through: :amenity_books
end
class Venue < ActiveRecord::Base
has_many :categorizations
has_many :amenities, through: :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :venue
belongs_to :amenity
end
class Book < ActiveRecord::Base
belongs_to :venue
end
class AmenityBook < ActiveRecord::Base
belongs_to :amenity
belongs_to :venue
belongs_to :book
end
这是一个改进的版本:
amenities_id_choosen = [1,3]
if book.save
Amenitiy.find(amenities_id_choosen).each do |amenity|
amenity.amenity_books.create(venue_id: venue.id)
end
end
这将导致一个SELECT查询找到所有选定的便利设施,并为每个选定的便利设施一个INSERT查询。
另一个选择是更改数据模型,AmenityBook
真的需要一个场所吗?因为看起来场地已经通过Book
模型定义了。
这是一个建议:
class Book < ActiveRecord::Base
belongs_to :venue
has_many :amenity_books
has_many :amenities, through: :amenity_books
end
class AmenityBook < ActiveRecord::Base
belongs_to :amenity
belongs_to :book
has_one :venue, through: :book
end
创建具有许多便利设施的预订的代码:
amenities_id_choosen = [1,3]
book.amenity_ids = amenities_id_choosen
if book.save
# success !
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句