2012-08-02 58 views
3
<%= collection_select(:catgory, :id, @categories, :id, :title, {}, data: { behavior: 'category_dropdown' }) %> 

在上面的代碼中,我需要將參數傳遞給title方法。有沒有辦法用collection_select來做到這一點?將參數傳遞給text_method的集合選擇方法

<%= collection_select(:catgory, :id, @categories, :id, (:title, @program), {}, data: { behavior: 'category_dropdown' }) %> 

編輯: 縱觀內部的collection_select的text_method。它最終傳遞給.send方法,該方法應該允許element.send(:title,@program)。但是,我認爲爲什麼仍然無法傳遞參數的問題是,collection select正在讀取(:title,@program)作爲兩個參數而不是一個參數。

+0

你有訪問在您的類別模型中使用@program? – InternetSeriousBusiness 2012-08-02 16:41:19

+0

不幸的是它是一個has_many關係,所以我需要通過程序來知道哪個程序要放在標題中。 – John 2012-08-02 16:42:45

回答

1

使用select代替:

select "catgory", "id", @categories.map{|c| [c.title(@program), c.id]}, {}, data: { behavior: 'category_dropdown' } 

應該是工作。

+0

對不起,括號內有錯誤:) – 2012-08-02 17:56:05

+0

沒問題。我很高興有一個解決方案。謝謝! – John 2012-08-02 18:08:12

0

這可以用collection_select可以做,如果你的模型現有的參數可以覆蓋:

f.collection_select(:your_model_id, 
    YourModel.all.map{|ym| ym.name = ym.custom_name(your_parameter); ym}, 
    :id, :name, 
    {:selected => @model_instance.logic}, 
    {:class => 'your class', :other => "..." }) 

比如我這樣做是爲了有條件變複數我的模型的name屬性

class MyModel < ActiveRecord::Base 
    DEFAULT_NAME_COUNT = 99 

    def pluralized_name(n = DEFAULT_NAME_COUNT) 
    begin 
     return name.pluralize(n) 
    rescue 
    end 

    name 
    end 
end