2014-10-31 38 views
4

在我的轨道项目中,我有三个型号:ActiveRecord如何将现有记录添加到has_many中的关联:通过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:通过设置,我如何可以采取定配方,像这样:

@recipe = Recipe.first 

,并添加一个类别这份食谱基于现有的类别,并且在相应的类别上进行更新。

所以:

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

然后

@category.recipes 

将包含@recipe?

我之所以问这个问题,是因为我试图通过gem rails_admin来实现这种行为,并且每次创建新的recipe对象时,指定它的类别的表单都是创建新类别的表单,而不是将现有的附加到这个配方。

因此,了解ActiveRecord如何将现有记录与many_to_many关系中新创建的记录相关联会有所帮助。

谢谢。

回答

9

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

,如果你需要添加一个当前category@recipe.categories,你只需要:

@recipe.categories << @category 

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

现在@category.recipes将包括@recipe

+0

谢谢! Isnt <<移位运算符? – 2014-10-31 01:36:00

+0

看看[has_many](http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many) – mohameddiaa27 2014-10-31 01:42:21

+0

@AdamBronfin不是真的。 http://stackoverflow.com/questions/6852072/what-does-mean-in-ruby – 2017-02-08 07:41:05

相关问题