Rails has_many belongs_to关系

时间:2013-05-23 05:25:40

标签: ruby-on-rails has-many belongs-to

我有一个非常基本的问题,但似乎无法让它正常工作。

这是设置 -

class Recipe < ActiveRecord::Base
 has_many :recipeIngredients
 has_many :ingredients :through => :recipeIngredients
end

class Ingredient < ActiveRecord::Base
 has_many :recipeIngredients
 has_many :recipes :through => :recipeIngredients
end

class RecipeIngredients < ActiveRecord::Base
 belongs_to :recipe
 belongs_to :ingredients
end

每种成分都有ID和名称,Recipe有ID和标题,RecipeIngredients有recipe_id,ingredient_id,金额

当我尝试使用

进行渲染时
@recipe = Recipe.find(params[:id])
render :json => @recipe, :include => :ingredients

我得到了我的成分,但无法从RecipeIngredients访问金额或名称。 - 这输出

{
    "list_items": {
        "id": 1,
        "title": "Foo",
        "description": null,
        "ingredients": [
            {
                "id": 1
            },
            {
                "id": 2
            },
            {
                "id": 3
            },
            {
                "id": 4
            }
        ]
    }
}

如何在成分和配方成分之间建立关系,以便在调用时:我会得到类似的东西 -

{
 "id":1,
 "name":"foo",
 "amount":"2 oz"
}

谢谢!

1 个答案:

答案 0 :(得分:2)

根据Rails,你没有定义多对多。正确的解决方案是(文件名应该如上所述):

应用/模型/ recipe.rb

class Recipe < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :ingredients, :through => :recipe_ingredients
end

应用/模型/ ingredient.rb

class Ingredient < ActiveRecord::Base
  has_many :recipe_ingredients
  has_many :recipes, :through => :recipe_ingredients
end

应用/模型/ recipe_igredient.rb

class RecipeIngredient < ActiveRecord::Base
  belongs_to :recipe
  belongs_to :ingredient
end

同时验证,您的连接表定义如下:

<强>分贝/ 12345_create_recipe_ingredints.rb

class CreateRecipeIngredients < ActiveRecord::Migration
  def change
    create_table :recipe_ingredients, id: false do |t|
      t.references :recipe
      t.references :ingredient
    end
    add_index :recipe_ingredients, :recipe_id
    add_index :recipe_ingredients, :ingredient_id
  end
end

执行此操作后,在控制台中进行测试:

recipe = Recipe.first # should contain data
igredient = Ingredient.first # should contain data
recipe.ingredients << ingredient
recipe.inspect

如果一切正常并且 recipe.inspect 包含成分,则json应该是正确的