ransackでの検索実装に伴い、scopeを作成しています。
親モデルであるUserモデルと、子モデルであるUserBasicモデルのリレーションをscope内でうまく表現したいのですができません。
現在、子モデルの:birthdayからデータを引っ張ってくるため、以下の様なscopeを作成しています。
Ruby
1class User < ActiveRecord::Base 2 has_one :user_basics 3 4 scope :by_age_to, -> (input){ 5 where("birthday >= ?", Date.strptime((Date.today.strftime("%Y%m%d").to_i - input.to_i * 10000 ).to_s, "%Y%m%d")) 6 } 7 8 scope :by_age_from, -> (input){ 9 where("birthday <= ?", Date.strptime((Date.today.strftime("%Y%m%d").to_i - input.to_i * 10000 ).to_s, "%Y%m%d")) 10 } 11 12 def self.ransackable_scopes(auth_object=nil) 13 %i[by_age_to by_age_from] 14 end 15 16end 17 18#users_controller.rb 19class UsersController < ApplicationController 20 21 def search 22 @q = User.search(params[:q]) 23 if params[:q].blank? 24 @users = User.search(params[:q]).result(distinct: true) 25 else 26 @users = @q.result(distinct: true) 27 end 28 end 29 30end
上記のようにオリジナルのransackの検索条件を作成しています。
この状態だと、Userはbirthdayカラムを持たない、とエラーを吐いてしまいます。
うまく記述する方法はないでしょうか。
ご回答いただけますと幸いです。
よろしくお願いいたしますm(__)m
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。