我有兩個模型,user
和profile
。用戶有一個配置文件。用ransack搜索用戶個人資料
# profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
end
# user.rb
class User < ActiveRecord::Base
has_one :profile
end
# routes.rb
resources :users do
resource :profiles, except: [:index, :show]
end
# users_controller.rb
class UsersController < ApplicationController
def index
@users = User.includes(:profile)
end
end
# users/index.html.erb
<% @users.each do |user| %>
<% if user.profile %>
<%= user.name %>
<%= user.interest %>
<% end %>
<% end %>
現在,我想添加ransack
gem來搜索用戶配置文件。這裏是我的當前設置:
# routes.rb
resources :users do
collection do
match 'search' => 'users#search', via: [:get, :post], as: :search
end
resource :profile, except: [:index, :show]
end
# users_controller.rb
class UsersController < ApplicationController
def index
@search = User.ransack(params[:q])
@users = @search.result.includes(:profile)
end
def search
index
render :index
end
end
# users/index.html.erb
<%= search_form_for @search, url: search_users_path, method: :post, do |f| %>
<%= f.search_field :name_cont, placeholder: 'Name' %><br>
<%= f.search_field :interest_cont, placeholder: 'Hobby' %><br>
<%= f.submit 'Search %>
<% end %>
但是我得到這個錯誤:
NoMethodError in Users#index
undefined method `name_cont' for Ransack::Search<class: User, base: Grouping <combinator: and>>:Ransack::Search
<%= f.search_field :name_cont, placeholder: 'Name' %><br>
這有什麼錯我的代碼?我應該巢搜索路線的輪廓,而不是用戶,所以它看起來是這樣的:
# routes.rb
resources :users do
resource :profile, except: [:index, :show] do
match 'search' => 'profiles#search', via: [:get, :post], as: :search
end
end
那麼,如何設置的休息嗎?謝謝。
按照慣例的Ransack要求您創建字段,如 _cont。用戶模型必須包含屬性'name',這是我相信的問題。 –
@MuhammadYawarAli事情是,名稱和興趣包含在屬於用戶模型的Profile模型中。 –
然後在profile用戶模型上應用ransack:'@search = Profile.ransack(params [:q]) @users = @ search.result.includes(:user)' –