0
0

More than 5 years have passed since last update.

ransackの検索条件に検索対象テーブルにない項目を入れる

Posted at

初心者です。検索にransackを使用していますが、ransackで使用する日付などといっしょに、geocoderで周辺検索に使用する位置情報もコントローラーに渡したいと考えました。
メンターさんにform_tagを使えばできると教えていただき、今回はセレクトボックスにしたかったので、select_tagを使うことでできました(メンターさんありがとうございました)。

huntsテーブル(検索対象テーブル)
レコード登録時に現在地をGoogleMapAPIで取得して以下カラムに保存
float :latitude
float :longitude

riverpointsテーブル(マスタ)
渓流のポイント情報についてのマスタ
string :riverpoint_name
decimal :riverpoint_latitude, :precision => 9, :scale => 6
decimal :riverpoint_longitude, :precision => 9, :scale => 6

hunts_controller.rb
def index
  # 検索の選択肢をviewに渡す
  @riverpoint = Riverpoint.all
end
hunts/index.html.erb
<%= search_form_for @search do |f| %>
  <%= select_tag :river_point, options_from_collection_for_select(@riverpoint, :id, :riverpoint_name), :prompt => "(選択)" %>
hunts_controller.rb
def index
  # index.htmlから絞り込むポイントの位置情報を受け取る
  riverpoint_id = params[:river_point]
  # ポイント絞込みに使う位置情報を作成
  if riverpoint_id.present?
    riverpoint = Riverpoint.find(riverpoint_id)
    latitude = riverpoint.riverpoint_latitude.to_f
    longitude = riverpoint.riverpoint_longitude.to_f
  end

  if latitude.present? #ポイント絞込みあり
    # geocoderのnearメソッドで絞り込み
    @hunts = @result.near([latitude, longitude], 0.2, units: :km)
  end
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0