Rails - 显示部分连接表属性

时间:2016-06-16 20:18:22

标签: ruby-on-rails activerecord rails-activerecord

我有两种模式:

  1. 路线 has_many:详情
  2. 明细 belongs_to:route
  3. 在Route模型中,我定义了以下范围:

    scope :origin_city_name, -> (origin) { where origin_city_name: origin }
    scope :destination_city_name, -> (destination) { where destination_city_name: destination }
    

    routes_controller.rb 中,我的自定义操作定义如下:

    def getstring
      ...
      @routes = Route.origin_city_name(from)
                .destination_city_name(to)
                .joins(:details)
                .order('details.departure ASC')
    end
    

    routes / getstring.html.erb 视图中,我有以下内容:

    <%= render @routes %>
    

    然后在 routes / _route.html.erb partial:

    <%= route.origin_station_name %>
    <%= route.destination_station_name %>
    <%= route.price %>
    

    其中price是详细信息的属性。

    当我运行服务器时,我收到以下错误:

      

    #Route的未定义方法`price':0x00000004054598

    另外,如果我在_route partial中调用route.inspect,我会得到一个“普通”Route对象,而不是连接表的对象。

    我做错了什么? 感谢

2 个答案:

答案 0 :(得分:1)

试试这个:

def getstring
  ...
  @routes = Route.origin_city_name(from)
            .destination_city_name(to)
            .joins(:details)
            .select("routes.*, details.price AS price")
            .order('details.departure ASC')
end

答案 1 :(得分:1)

由于Route has_many DetailspriceDetail的模型属性,您应该执行以下操作以迭代所有他们:

<% route.details.each do |detail| %>
  <%=detail.price%>
<% end %>