link_to text - 为html文本使用ruby代码

时间:2013-03-18 00:24:23

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

我希望我视图上的链接文本显示为Hospital,Country。国家/地区是指南属性,因此我需要能够从“医院”访问guidelines.country并显示它

e.g。得到医院,Sickland

我不确定如何正确编码。目前在我的视图文件中我有

<% @list.each do |hospital| %>

        <tr class="tablerow">
            <td><%= link_to (hospital, country), :action => :topichospital, :hospital => hospital, :country=>country %></td>
        </tr>

当我刚刚工作时,它有效,但我不确定如何添加国家

 <% @list.each do |hospital| %>

            <tr class="tablerow">
                <td><%= link_to hospital, :action => :topichospital, :hospital => hospital %></td>
            </tr>

我在guidelines_controller.rb中的listhospital操作是

def listhospital
    @list = Guideline.order(:hospital).uniq.pluck(:hospital)
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @guidelines }
    end
  end

2 个答案:

答案 0 :(得分:1)

将您的link_to更改为

<%= link_to "#{hospital}, #{country}", { :action => :topichospital, :hospital => hospital, :country=>country } %>

这将转换传递给string的第一个参数。我不确定当作为第一个参数传递时,rails如何解释link_to中的(hospital, country),但这将确保为每个参数调用to_s方法。

更新:IIRC,您可以使用pluck来合并属性

# postgre
@list = Guideline.order(:hospital).uniq.pluck("hospital || ', ' || country")

# mysql
@list = Guideline.order(:hospital).uniq.pluck("CONCAT(hospital, ', ', country)")

然后您可以在视图中使用link_to hospital

更新:这变得有点黑客了。我建议你把控制器更改为

@list = Guideline.select('hospital, country').order(:hospital).uniq

然后在你看来

<% @list.each do |guideline| %>
  <tr class="tablerow">
    <td><%= link_to "#{guideline.hospital}, #{guideline.country}", { :action => :topichospital, :hospital => guideline.hospital, :country => guideline.country }%></td>
  </tr>
<% end %>

答案 1 :(得分:0)

我认为你在寻找:

<%= link_to "#{hospital}, #{country}", :action => :topichospital, :hospital => hospital, :country=>country %>

你也可以将一个块传递给link_to

<%= link_to :action => :topichospital, :hospital => hospital, :country=>country do %>
  <%= hospital %>, <%= country %>
<% end %>

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to