2014-10-09 57 views
1
class HellosController < ApplicationController 


    def index 
    #do sth here 
    end 

    def new 
    #do sth here 
    end 

    def edit 
    #do sth here 
    end 

    def report 
    #how can I display different format of report according to diff value of a variable ?  
    end 

end 

我知道在控制器的每个不同的功能,可以有一个观点,现在我有这个报告链接到一个报告view.I需要补充报告的观点为这个项目。Ruby on Rails的控制器中的一个功能有不同的看法

如何根据变量显示不同的视图say @reportType? 我需要添加到控制器中?我应该如何命名添加的报告视图?

回答

2

您可以检查@report_typereport.html.erb

例如: 在report.html.erb

<% if @report_type == "this" %> 
<%= render partial: "this" %> 
<% elsif @report_type == "that" %> 
<%= render partial: "that" %> 
<% end %> 

在这里,您将有两个谐音一样

_this.html。 erb and _that.html.erb

通过这种方式,您可以针对报告类型拥有适当页面的多个视图。

0
在您的链接

发送report_id作为参数

= link_to "See report", your_report_path + "?report_id=" + report.id 

在你report行动

def report 
    @reportType = ReportModel.find params(:report_id) 
end 

report.html.erb,你可以使用这个变量,例如

Name of the report is <%= @reportType.name %> 
+0

谢谢!你能解释一下吗?我的报告没有任何链接,在我看来它叫做report.html.erb - 我认为它们是通过名字转换链接的。如何将这个名称链接改为你的方法?以及第二个报告视图在哪里添加以及如何命名? – Orz 2014-10-09 09:12:58

+0

你打算如何报告页面,通过点击一些链接的权利? – RSB 2014-10-09 09:13:56

+0

我已经把问题报告的内容,似乎没有链接那里...在应用程序中,当我点击一个按钮称为报告,报告页面将显示 – Orz 2014-10-09 09:18:27

1

在控制器,你可以渲染不同的网页,如果条件

如:

 
if [condition] 
    render "abc" 
else 
    render "xyz" 
end 
1

很容易的。这样的事情裸机例子是:

class ReportsController < ApplicationController 
    def show 
    @report = Report.find(params[:report_id]) 
    if @report.type == "special" 
     # This will render app/view/special_report.html.erb 
     render :special_report 
    else 
     # This will render app/view/report.html.erb 
     render :report 
    end 
    end 
end 

当然,还有比这多很多,look at the Rails guides for other options。注意我正在使用符号来指定视图。你不必这样做,字符串也可以,例如"report""special_report"

相关问题