我有两个模型,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)' –