2016-03-30 61 views
0

我有两个模型,userprofile。用户有一个配置文件。用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 

那么,如何设置的休息吗?谢谢。

+0

按照惯例的Ransack要求您创建字段,如 _cont。用户模型必须包含属性'name',这是我相信的问题。 –

+0

@MuhammadYawarAli事情是,名称和兴趣包含在属于用户模型的Profile模型中。 –

+0

然后在profile用户模型上应用ransack:'@search = Profile.ransack(params [:q]) @users = @ search.result.includes(:user)' –

回答

0

我的错误,我不仔细阅读文档。我只需要在视图中使用这些内容:

<%= search_form_for @search, url: search_users_path, method: :post, do |f| %> 
    <%= f.search_field :profile_name_cont, placeholder: 'Name' %><br> 
    <%= f.search_field :profile_interest_cont, placeholder: 'Hobby' %><br> 
    <%= f.submit 'Search %> 
<% end %> 
0

您需要将ransacker方法添加到您的用户模型中。示例可以找到here

在User.rb

ransacker :name_cont, formatter: proc { |v| 
    data = User.joins(:profile).where('profile.name = ?', v).map(&:id) 
    data = data.present? ? data : nil 
}, splat_param: true do |parent| 
parent.table[:id] 
end 

我还没有测试此代码。

+0

你能详细说一下吗?我仍然没有得到它。 –