【问题标题】:ruby on rails reuse a viewruby on rails 重用视图
【发布时间】:2012-06-16 18:34:31
【问题描述】:

我有一个“食谱”表和一个“成分”表。每个配方“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)

谢谢, 李

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    像这样:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多