Ich habe zwei Modelle, user
und profile
. Der Benutzer hat ein Profil.Benutzerprofil mit ransack suchen
# 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 %>
Jetzt will ich ransack
gem hinzufügen Benutzerprofilen zu suchen. Hier ist meine aktuelle Setup:
# 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 %>
Jedoch habe ich diesen Fehler:
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>
Was mit meinem Code falsch? Soll ich Nest die Suchweg zum Profil anstelle von Benutzern, so dass es wie folgt aussieht:
# routes.rb
resources :users do
resource :profile, except: [:index, :show] do
match 'search' => 'profiles#search', via: [:get, :post], as: :search
end
end
Dann, wie der Rest Setup? Vielen Dank.
Ransack nach Konvention erfordert, dass Sie Felder wie _cont erstellen. Benutzermodell muss ein Attribut 'name' enthalten, das ist das Problem, das ich glaube. –
@MuhammadYawarAli die Sache ist, der Name und das Interesse sind im Profilmodell enthalten, das zum Benutzermodell gehört. –
dann anwenden ransack auf Profil nicht Benutzermodell wie: '@search = Profil.ransack (params [: q]) @users = @ search.result.includes (: Benutzer)' –