【问题标题】:pass a parameter to collection_select's text_method in Rails在 Rails 中将参数传递给 collection_select 的 text_method
【发布时间】:2016-04-02 10:44:15
【问题描述】:

我有以下几点:

<%= collection_select 'product', 'id', @products, 'id', :description %>

- 与前面的关键字搜索匹配的产品列表。

我想使用更具体的描述,它是由模型的方法specific_description(keyword)构建的。尽管模型无权访问关键字(params [:q])。 使用collection_select时,可以使用什么将参数传递给text_method(在我的例子中是描述)?

【问题讨论】:

    标签: ruby-on-rails collection-select


    【解决方案1】:

    attr_accessor :keyword 添加到Product 模型并在specific_description 中使用它:

    class Product < ActiveRecord::Base
      attr_accessor :keyword
    
      def specific_description
        # use @keyword here
      end
    end
    

    在控制器中:

    @products.each { |product| product.keyword = params[:q] }
    

    现在您可以在不向specific_description 传递参数的情况下调用collection_select

    <%= collection_select 'product', 'id', @products, 'id', :specific_description %>
    

    【讨论】:

      猜你喜欢
      • 2021-10-04
      • 2016-02-02
      • 1970-01-01
      • 2011-09-19
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多