GMA*_*GMA 5 ruby activerecord ruby-on-rails associations has-many-through
我有模型User,Photo并且Favorite,那里favorites是从连接表users到photos,即:
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
Run Code Online (Sandbox Code Playgroud)
说,@user是一个实例User并且photo_ids是图片的主键的阵列.将所有这些照片添加到最快和/或最简洁的方式是@user.photos什么?
我能做的最好的是:
@user.favorites.create( photo_ids.map { |id| {photo_id: id } } )
Run Code Online (Sandbox Code Playgroud)
但这对我来说似乎很啰嗦.Rails没有更好的处理方法吗?
其他问题讨论has_many: through:通过嵌套表单创建多个关联,但我试图在JSON API中执行此操作,因此不涉及任何表单.
怎么样
@user.photos << Photo.find_all_by_id(photo_ids)
Run Code Online (Sandbox Code Playgroud)