ruby-on-rails – 通过ID数组中的关联创建多个has_many
发布时间:2020-12-17 03:23:34 所属栏目:百科 来源:网络整理
导读:我有模特用户,照片和收藏夹,其中收藏夹是从用户到照片的连接表,即: class User ActiveRecord::Base has_many :favorites has_many :photos,through: `favorites`endclass Photo ActiveRecord::Base has_many :favorites has_many :users,through: `favorite
我有模特用户,照片和收藏夹,其中收藏夹是从用户到照片的连接表,即:
class User < ActiveRecord::Base has_many :favorites has_many :photos,through: `favorites` end class Photo < ActiveRecord::Base has_many :favorites has_many :users,through: `favorites` end class Favorite < ActiveRecord::Base belongs_to :user belongs_to :photo end 假设@user是User的实例,photo_ids是Photos的主键数组.将所有这些照片添加到@ user.photos的最快和/或最简洁的方法是什么? 我能做的最好的是: @user.favorites.create( photo_ids.map { |id| {photo_id: id } } ) 但这对我来说似乎很啰嗦. Rails没有更好的处理方法吗? 其他问题讨论创建多个has_many:through:通过嵌套表单的关联,但我试图在JSON API中执行此操作,因此不涉及任何表单. 解决方法
怎么样
@user.photos << Photo.find_all_by_id(photo_ids) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |