【问题标题】:Filter collection with select dropdown in Rails with Ransack在带有 Ransack 的 Rails 中使用选择下拉列表过滤集合
【发布时间】:2015-08-12 22:02:39
【问题描述】:

我是 Ransack 的新手,我很难得到我想要的结果。如果有人可以阐明我将不胜感激。 我正在尝试按“城市”为视图统计/索引中的 ship_projects 集合创建一个过滤器,并且我正在使用 Ransack。

模型ShipProjectsCities 相距甚远,有很多关系。

ship_projects ship_groups shipments > belongs_to people

postal_addresses > belongs_to 城市

模型

class ShipProject < ActiveRecord::Base
  has_many :ship_groups
  has_many :shipments, through: :ship_groups

class ShipGroup < ActiveRecord::Base
  belongs_to :ship_project
  has_many :shipments

class Shipment < ActiveRecord::Base
  belongs_to :person
  belongs_to :ship_group

class Person < ActiveRecord::Base
  has_many :postal_addresses
  has_many :cities, through: :postal_addresses

class PostalAddress < ActiveRecord::Base
  belongs_to :person
  belongs_to :city

class City < ActiveRecord::Base
  has_many :postal_addresses

统计控制器

  def index
    @q = ShipProject.ransack(params[:q])
    @ship_projects = @q.result.includes(:people, :cities)
    respond_to do |format|
      format.html
      format.xlsx { render xlsx: 'index', filename: 'reporte_envios.xlsx' }
    end
  end

statistics/index.html.erb

<%= search_form_for @q do |f| %>
  <div class='form-inline form-group'>
    <div class='row'>
      <div class='col-md-4'>
        <%= f.label :city_id_eq, "City" %><br/>
        <%= f.select :city_id_eq, options_from_collection_for_select(City.all.order(:name), :id, :name, @q.city_id_eq), { }, {class: 'form-control'} %>
      </div>
      <div class="col-md-4">
        <%= f.submit "Filter", class: 'btn btn-info btn-block' %>
      </div>
    </div>
  </div>
<% end %>

在控制台中我收到以下错误:

Started GET "/statistics" for ::1 at 2015-08-12 17:51:39 -0500
Processing by StatisticsController#index as HTML
  User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 8  ORDER BY `users`.`id` ASC LIMIT 1
  Rendered layouts/_messages.html.erb (0.3ms)
  Rendered statistics/index.html.erb within layouts/application (5.2ms)
Completed 500 Internal Server Error in 12ms (ActiveRecord: 0.3ms)

NoMethodError - undefined method `city_id_eq' for #<Ransack::Search:0x007fc481bf3478>:

【问题讨论】:

    标签: ruby-on-rails filter ransack


    【解决方案1】:

    ShipProject db 表中添加city_id 列。然后添加合适的关系:

    ShipProject
      belongs_to :city
    
    City
      has_many :ship_projects
    

    那么,当您创建ShipProject 时,当然需要一种方法来保存city_id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2017-11-07
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多