【问题标题】:Search user profile with ransack用 ransack 搜索用户个人资料
【发布时间】:2016-03-30 12:20:04
【问题描述】:

我有两个模型,user 和 profile。用户有一个个人资料。

# 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 问题是,名称和兴趣包含在属于 User 模型的 Profile 模型中。
  • 然后在配置文件而不是用户模型上应用洗劫,例如:@search = Profile.ransack(params[:q]) @users = @search.result.includes(:user)
  • @MuhammadYawarAli 我需要索引操作位于用户控制器中,搜索操作位于配置文件控制器中。

标签: ruby-on-rails ransack


【解决方案1】:

您需要将 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

我没有测试过这段代码。

【讨论】:

  • 您能详细说明一下吗?我还是没听懂。
【解决方案2】:

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

<%= 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 %>

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多