【问题标题】:Creating multiple has_many through associations from an array of IDs通过 ID 数组的关联创建多个 has_many
【发布时间】:2014-02-05 03:22:09
【问题描述】:

我有模型UserPhotoFavorite,其中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

假设@userUser 的一个实例,photo_ids 是一组照片的主键。将所有这些照片添加到 @user.photos 的最快和/或最简洁的方法是什么?

我能做到的最好的是:

@user.favorites.create( photo_ids.map { |id| {photo_id: id } } )

但这对我来说似乎很冗长。 Rails 没有更好的方法来处理这个问题吗?

其他问题涉及通过嵌套表单创建多个 has_many: through: 关联,但我尝试在 JSON API 中执行此操作,因此不涉及任何表单。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations has-many-through


    【解决方案1】:

    怎么样

    @user.photos << Photo.find_all_by_id(photo_ids)
    

    【讨论】:

    • 没有意识到您可以在 ActiveRecord 关联上使用 &lt;&lt;。谢谢!
    • 另请注意,右边的对象是一个数组 - 但它仍然有效。
    • 其实我觉得这行不通,Photo.find_by_id不会只返回一个结果吗? Photo.where(id: photo_ids)Photo.find(photo_ids) 都可以正常工作。
    • 酷。值得注意的是 find_by_*find_all_by_* 语法在 Rails 4 中已弃用。我使用了 where 但效果是一样的。
    • 在 Rails 4 中,我可能会选择 find_all_by(id: photo_ids) - 在这里感觉比 where 略好,但显然没有区别。 :) 另请注意,如果 Photo.find(photos_id) 找不到任何记录,它将引发异常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多