2017-06-13 83 views
1

所以我有2個模型。Rails如何獲得映射字段的id到下拉列表

Countries 
name:string 

Descriptions 
title:string 
text:string 
country_id:integer 

` 如何添加國家ID爲說明,當我從下拉列表中選擇國家?

<%= form_for @description, :url => {:action => "create", :id => "#{@tour.id}" }, :html => { :multipart => true } do |f| %> 

<%= f.label :Title %><br/> 
<%= f.text_field :title %><br/> 

<%= f.label :Desc %><br/> 
<%= f.text_field :text %><br/> 

<%= f.select :city, (@cities.map { |l| [l.name, l.name] }) %> 


<%= f.submit "Add"%> 

<% end %> 

控制器

def new 
    @description = Description.new 
    @tour = Tour.find(params[:id]) 
    @cities = City.all 
... 
    end 

def create 
    @tour = Tour.find(params[:id]) 
    @description = @tour.descriptions.build(description_params) 
end 

我會感激的你可以嘗試使用collection_select任何提示或有用的鏈接:)

回答

0

實施例:

f.collection_select :country_id, Country.all, :id, :name 

第一參數(:COUNTRY_ID)是被髮送到後端的PARAM的名稱。

第二個參數是用來填充選項的記錄集合。

第三個參數指定選項值。在這種情況下,你想用id填充它,所以我們把:id

第四個參數指定選項的標籤,這是選項的人類可讀名稱。在這種情況下,你可能想要國家的名字,所以我們把:country

+0

它的工作非常感謝你 – Yurii10

+0

我的榮幸。很高興我能幫上忙。 –