【发布时间】: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