1

我有一个“食谱”表和一个“成分”表。每个配方“has_and_belong_to_many”成分和每种成分“has_and_belong_to_many”配方。

我想添加一个指向成分页面的链接:“显示所有包含该成分的食谱”。

我在成分控制器中编写了以下代码:

def recipes
    @ingredient = Ingredient.find(params[:id])
    @recipes = @ingredient.recipes
    respond_to do |format|
       format.html # index.html.erb
       format.json { render json: @recipes }
    end
end

我的问题是现在它希望我在“成分”视图下有一个“recipes.html.erb”文件。我不想为此创建一个新视图,我只想使用我在“食谱”视图 (recipes/index.html.erb) 中使用的相同代码。我怎样才能将rails引导到这个视图?

(我使用的是 Rails 3.x)

谢谢,李

4

1 回答 1

2

像这样:

def recipes
    @ingredient = Ingredient.find(params[:id])
    @recipes = @ingredient.recipes
    respond_to do |format|
       format.html { render "recipes/index" }
       format.json { render json: @recipes }
    end
end

详情请看rails指南: http: //guides.rubyonrails.org/layouts_and_rendering.html#using-render

于 2012-06-16T10:33:13.837 回答