我是Ruby on Rails的新手.在Rails应用程序中,我看到了一些如下代码:
在模型中,有一个类Car:
class Car < ActiveRecord::Base
...
end
Run Code Online (Sandbox Code Playgroud)
在控制器中,有一个方法" some_method "
class CarsController < ApplicationController
def some_method
@my_car = Car.new()
#What does the following code do?
#What does "<<" mean here?
@my_car.components << Component.new()
end
end
Run Code Online (Sandbox Code Playgroud)
我有三个问题要问:
1.在控制器的代码中@my_car.components << Component.new(),它做了什么?什么<<意思?
2.在Ruby-On-Rails或Ruby中是否还有其他"<<"用法?
3.如果使用" << " ,类是否Car必须显式定义has_many与Component类的关联或者是否可以使用" << "添加新关联,即使关联未在类中明确定义?CarCar
在我的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
Run Code Online (Sandbox Code Playgroud)
有了这个简单的has_many:通过设置,我该如何处理给定的食谱:
@recipe = Recipe.first
Run Code Online (Sandbox Code Playgroud)
并根据现有类别向此配方添加类别,并在相应类别上更新.
所以:
@category = #Existing category here
@recipe.categories.build(@category)
Run Code Online (Sandbox Code Playgroud)
然后
@category.recipes
Run Code Online (Sandbox Code Playgroud)
将包含@recipe?
为什么我问这个是因为我想要实现通过创业板rails_admin这种行为,我每次创建新配方的对象,形式,将其指定的类别的原因是为了创建一个新的类别,而不是附加的形式现有的一个配方.
因此,理解ActiveRecord如何将现有记录与many_to_many关系中新创建的记录相关联将会很有帮助.
谢谢.