嵌套属性中的关联参数

时间:2016-05-05 21:07:36

标签: ruby-on-rails-4 rspec associations factory-bot nested-attributes

我有三个型号。食谱,成分,阶段。

recipe.rb

class Recipe < ActiveRecord::Base
belongs_to :user
has_many :ingredients, inverse_of: :recipe, dependent: :destroy
has_many :stages, inverse_of: :recipe, dependent: :destroy
accepts_nested_attributes_for :ingredients
accepts_nested_attributes_for :stages
end

stage.rb

class Stage < ActiveRecord::Base
belongs_to :recipe, inverse_of: :stages
has_many :ingredients, inverse_of: :stage
end

ingredient.rb

class Ingredient < ActiveRecord::Base
belongs_to :recipe, inverse_of: :ingredients
belongs_to :stage, inverse_of: :ingredients
end

我不确定params_controller应该有多强的params。我现在有类似的东西:

 def recipe_params
      params.require(:recipe).permit(ingredients_attributes: [:id, :stage_id] , stages_attributes: [:id])
    end

这是对的吗?我也不确定rspec测试应该如何寻找它。

 let(:valid_params) { FactoryGirl.attributes_for(:recipe, :user => user, ingredients_attributes: [FactoryGirl.attributes_for(:ingredient, :stage => ???)], stages_attributes: [FactoryGirl.attributes_for(:stage)]) }

it "should create recipe" do
          expect { post :create, :recipe => valid_params}.to change(Recipe, :count).by(1).and change(Ingredient, :count).by(1).and change(Stage, :count).by(1)
        end

0 个答案:

没有答案