0

我希望我的视图上的链接文本显示为医院,国家。Country 是一个guidelines 属性,所以我需要能够从'hospital' 访问guidelines.country 并显示它

例如 Get Well 医院、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
4

2 回答 2

1

将您的 link_to 更改为

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

这会将传递的第一个参数转换为字符串。我不确定rails(hospital, country)在作为第一个参数传递时如何解释link_to,但这将确保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 %>
于 2013-03-18T00:34:45.187 回答
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

于 2013-03-18T00:34:41.230 回答