3

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

这是设置 -

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 和一个 Title,RecipeIngredients 有 recipe_id、component_id、amount

当我尝试使用

@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
            }
        ]
    }
}

我怎样才能在成分和recipeIngredients之间建立关系,以便在调用:ingredients时我得到类似 -

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

谢谢!

4

1 回答 1

2

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

应用程序/模型/recipe.rb

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

应用程序/模型/成分.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

还要验证您定义的连接表,如下所示:

db/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 应该是正确的

于 2013-05-23T06:01:39.107 回答