Ruby on rails Ransack:显示按Ransack排序的多个关系的属性

Ruby on rails Ransack:显示按Ransack排序的多个关系的属性,ruby-on-rails,ruby,ransack,Ruby On Rails,Ruby,Ransack,我有商品(名称:string)模型和价格(金额:浮动)模型,以便: class Commodity < ApplicationRecord has_many :prices end 我现在正在使用prices.first.amount作为占位符。如何用分拣时发现的数量替换此值?需要澄清的是,其中缺少一些信息,但很简单。你甚至可以得到答案,如果你有你发布的例子中的关联,那么它必须与你发送的代码一起工作 sort_link(@q, :prices_amount) 其中“prices”是

我有
商品(名称:string)
模型和
价格(金额:浮动)
模型,以便:

class Commodity < ApplicationRecord
  has_many :prices
end

我现在正在使用
prices.first.amount
作为占位符。如何用分拣时发现的
数量
替换此值?

需要澄清的是,其中缺少一些信息,但很简单。你甚至可以得到答案,如果你有你发布的例子中的关联,那么它必须与你发送的代码一起工作

sort_link(@q, :prices_amount)

其中“prices”是关联的名称,“amount”是您的属性。

我建议创建一个范围,将价格包含在
商品
实例中。e、 g

class Commodity < ApplicationRecord
  scope :with_price, -> {joins(:prices).select("commodities.*, prices.amount as price_amount")}
end
假设您将这些数据“显示”为一个表,您可以使用以下命令按要求显示结果

<table>
  <thead>
    <tr>
      <th><%= sort_link(@q, :name, 'Commodity' %></th>
      <th><%= sort_link(@q, :prices_amount, 'Price') %></th>
    </tr> 
  </thead>
  <tbody>
    <% @commodities.each do |commodity| %>
      <tr> 
        <td><%= commodity.name %></td>
        <td><%= number_to_currency(commodity.price_amount) %></td>
      </tr>
    <% end %>
  </tbody>
</table>


您能提供更多信息吗?你有一张商品表,上面显示了所有的商品,对吗?但是你想按价格排序,但是如果它有很多价格,你想怎么做呢?排序链接使用的商品价格越低,还是越大?请提供更多详细信息hi@xploshioOn,我已经编辑了我的问题。如果仍然不清楚我想要什么,我会再次编辑它。好的,它提供了更多细节,你能添加你现在拥有的代码来显示所有商品吗?@xploshioOn,我添加了显示商品的代码。太好了!这是辉煌的,简单的,正是我想要的。这可能也应该在Ransack文档中解释。@a3y3这实际上与
Ransack
无关,因为您提到您的排序工作正常,问题是您不确定是哪个价格导致了仓位。当您在
ActiveRecord
中运行select查询时,它会将所有列映射到活动记录实例的
attributes
,因此我们只是将
prices.amount
添加到别名
price\u amount
下的那些属性中,以便您知道是哪个价格导致了排序中的位置。很高兴你成功了。
class Commodity < ApplicationRecord
  scope :with_price, -> {joins(:prices).select("commodities.*, prices.amount as price_amount")}
end
@q = Commodity.ransack(params[:q])
@commodities = @q.result.with_price
<table>
  <thead>
    <tr>
      <th><%= sort_link(@q, :name, 'Commodity' %></th>
      <th><%= sort_link(@q, :prices_amount, 'Price') %></th>
    </tr> 
  </thead>
  <tbody>
    <% @commodities.each do |commodity| %>
      <tr> 
        <td><%= commodity.name %></td>
        <td><%= number_to_currency(commodity.price_amount) %></td>
      </tr>
    <% end %>
  </tbody>
</table>