【问题标题】:Rails 4 - Ransack usage with nested resources on parent show pageRails 4 - Ransack 使用父显示页面上的嵌套资源
【发布时间】:2016-10-04 02:48:55
【问题描述】:

所以在我的应用程序中,客户端有许多站点,我的路由和控制器嵌套在客户端下,它们都出现在显示页面上(代码如下)。

我想要实现的是在客户端显示页面上实现 Ransack 搜索表单和排序链接,以便用户可以搜索相关网站等。

目前,当我创建与客户端关联的站点时,无论站点与哪个客户端关联,它都会显示所有客户端的所有站点。

我的路线:

  resources :clients, controller: 'clients' do
    resources :sites, controller: 'clients/sites', except: [:index]
  end

客户端控制器/显示操作

 class ClientsController < ApplicationController 
      def show
        @client = Client.find(params[:id])

        @q = Site.ransack(params[:q])
        @sites = @q.result(distinct: true).page(params[:page]).per(5)
      end
end

我的模型:

class Client < ApplicationRecord
 has_many :sites, dependent: :destroy
end 

class Site < ApplicationRecord
 belongs_to :client
end

我在 Clients/show[:id] 页面上的搜索表单和排序链接

<%= search_form_for @q do |f| %>
 <%= f.search_field :site_ident_or_site_name_cont, :class => 'form-control', :placeholder => 'search client...' %>
<% end %>

<%= sort_link(@q, :site_name, 'Site Name') %>

我想要做的是只搜索与正在显示的客户端关联的网站。这里的任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 ransack


    【解决方案1】:

    我不熟悉 ransack,但我猜您应该使用关联来确定搜索范围,例如:

      def show
        @client = Client.find(params[:id])
    
        # scope by just the sites belonging to this client
        @q = @client.sites.ransack(params[:q])
        @sites = @q.result(distinct: true).page(params[:page]).per(5)
      end
    

    【讨论】:

    • 所以我得到了 {NoMethodError at /clients/1 undefined method `sites_path' for #:0x007f863ca6adc8> 你是说吗?资产路径}
    • 好吧,我想通了!你的帖子让我去了那里也需要对搜索表单进行一些更改。感谢您的帮助!
    【解决方案2】:

    所以解决方案是一个两部分的解决方案,这要感谢 Taryn East 的上述回答,让我顺利完成任务!

    控制器动作剂量需要像她建议的那样确定范围:

      def show
        @client = Client.find(params[:id])
    
        # scope by just the sites belonging to this client
        @q = @client.sites.ransack(params[:q])
        @sites = @q.result(distinct: true).page(params[:page]).per(5)
      end
    

    然后对搜索表单进行一些修改:

    <%= search_form_for @q, url: client_path(params[:id]) do |f| %>
     <%= f.search_field :site_name_cont, :class => 'form-control', :placeholder => 'search client...' %>
    <% end %>
    

    这解决了问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多