通过ID数组中的关联创建多个has_many

GMA*_*GMA 5 ruby activerecord ruby-on-rails associations has-many-through

我有模型User,Photo并且Favorite,那里favorites是从连接表usersphotos,即:

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中执行此操作,因此不涉及任何表单.

Bro*_*tse 6

怎么样

@user.photos << Photo.find_all_by_id(photo_ids)
Run Code Online (Sandbox Code Playgroud)

  • 凉.值得注意的是,在Rails 4中不推荐使用`find_by_*`和`find_all_by_*`语法.我使用`where`但效果是一样的. (4认同)
  • 在rails 4中,我可能会选择`find_all_by(id:photo_ids)` - 它感觉比这里的`where`略好,但显然没有区别.:)另请注意,如果找不到任何记录,Photo.find(photos_id)将引发异常. (2认同)