2013-08-31 21 views
0

如何將數據字段添加到此options_for_select中的選項?這是Rails的2如何將數據字段添加到Rails中options_for_select的選項中?

我想喜歡

data-masterlocation-name="<%= location.masterlocation.inst_name %>" 

data-masterlocation-id="<%= location.masterlocation.id %>" 

添加了一些每個選項。我嘗試遵循這種方法(Rails Formtastic: adding "data-" field to option tag),但它似乎不適合我的情況。在此先感謝您的幫助!

Maptry助手:

module MaptryHelper 

    def options_for_select(locations) 
    locations.map do |location| 
     [location.masterlocation.name, location_string(location.masterlocation)] 
    end 
    end 

    def location_string(masterlocation) 
    "#{masterlocation.street_address}, #{masterlocation.city}, #{masterlocation.state}, #{masterlocation.zip}" 
    end 

end 

查看

<%= f.select :start, options_for_select(@itinerary.locations),{}, :id=>"startdrop", :name=>"startthere" %>  

最終版本的Works

助手

module MaptryHelper 

    def options_for_select(locations) 
    locations.map do |l| 
    content_tag "option", l.masterlocation.name, location_option_attributes(l) 
    end.join("\n") 
    end 

    private 

    def location_option_attributes(location) 
    { 
    :value => "#{location.masterlocation.street_address}, #{location.masterlocation.city}, #{location.masterlocation.state}, #{location.masterlocation.zip}", 
    :id => location.masterlocation.id, 
    :"data-masterlocation-name" => location.masterlocation.name, 
    :"data-masterlocation-id" => location.masterlocation.id 
    } 
    end 
end 

查看

<%= f.select :start, options_for_select(@itinerary.locations), {}, {:id=>"startdrop", :name=>"startthere"} %>  
+0

這實際上是不正確。您可以。看到這裏:http://stackoverflow.com/questions/7624824/rails-formtastic-adding-data-field-to-option-tag – bcackerman

回答

0

你不能用這種方法做到這一點。但是,可以這樣寫:

<%= f.select :start, location_options(@itinerary),{}, :id=>"startdrop", :name=>"startthere" %>  

並在您的幫助:

def location_options(itinerary) 
    itinerary.locations.map do |l| 
    content_tag "option", l.name, location_option_attributes(l) 
    end.join("\n") 
end 

private 

def location_option_attributes(location) 
    { 
    :id => location.id, 
    :"data-masterlocation-name" => location.masterlocation.inst_name, 
    :"data-masterlocation-id" => location.masterlocation.id 
    } 
end 
+0

感謝您的評論!不幸的是,這會拋出一個錯誤:'maptry_helper.rb:3:形式參數不能作爲實例變量def location_options(@itinerary)^ .'另外,在你的答案中,我會在哪裏放置我想要創建的值:'' #{masterlocation.street_address},#{masterlocation.city},#{masterlocation.state},#{masterlocation.zip}「'? – KDP

+0

我能夠調整代碼以使其適用於我(基於上面的代碼!)感謝您的幫助。我在那裏有幾個相關的問題,所以感謝您提供的任何其他建議。 – KDP

相關問題