ruby-on-rails - ActiveRecord 如何将现有记录添加到 has_many :through relationship in rails? 中的关联

标签 ruby-on-rails ruby activerecord many-to-many rails-admin

在我的 Rails 项目中,我有三个模型:

class Recipe < ActiveRecord::Base
  has_many :recipe_categorizations
  has_many :category, :through => :recipe_categorizations
  accepts_nested_attributes_for :recipe_categories, allow_destroy: :true
end

class Category < ActiveRecord::Base
  has_many :recipe_categorizations
  has_many :recipes, :through => :recipe_categorizations
end

class RecipeCategorization < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :category
end

通过这个简单的 has_many :through 设置,我怎样才能像这样获取给定的食谱:

@recipe = Recipe.first

并根据现有类别向此食谱添加类别,并在相应类别上对其进行更新。

所以:

@category = #Existing category here
@recipe.categories.build(@category)

然后

@category.recipes

将包含@recipe?

我问这个的原因是因为我试图通过 gem rails_admin 实现这种行为,每次我创建一个新的食谱对象时,指定它的类别的表单就是创建一个新类别的表单,而不是而不是将现有的附加到此食谱。

因此,了解 ActiveRecord 如何以多对多关系将现有记录关联到新创建的记录会很有帮助。

谢谢。

最佳答案

build方法与 new 方法足够接近,用于创建新记录。

如果您需要将当前的类别添加到@recipe.categories,您只需:

@recipe.categories << @category

这将在 RecipeCategorization 表中添加一条记录(自动保存)。

现在 @category.recipes 将包含 @recipe

关于ruby-on-rails - ActiveRecord 如何将现有记录添加到 has_many :through relationship in rails? 中的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665494/

相关文章:

ruby-on-rails - postgres Gem::Ext::BuildError:在 OSX 上安装 'pg' 时无法构建 gem native 扩展

ruby - 运行 Ruby 终端的停止列表

sql - 是否存在关于 ActiveRecord 关系的困惑?方法,尤其是限制和偏移

ruby-on-rails - 让 Autotest 在 OS X 上与 Growl 一起工作

ruby-on-rails - 添加具有默认空值的列

arrays - 为什么我的 Ruby `for` 循环的效果没有持续存在?

ruby-on-rails - 没有 Gem 的 Rails 分页

ruby-on-rails - 这个模型应该如何设计?

ruby-on-rails - Rails 4 在remote=true 表单提交时显示ajax 加载器

ruby-on-rails - 乘客错过了生产环境中的开发 gem