2013-01-05 116 views
1

我想創建一個嵌套的表單欄,其中將同時創建兩個模型。該模型具有如下:創建兩個嵌套的模型

型號/活動

#Data 
    attr_accessible :customer_id, :description, :locations_attributes 
#Relationship 
    has_many :locations 
    accepts_nested_attributes_for :locations, :allow_destroy => true 

型號/地點

#Data 
    attr_accessible :address, :customer_id, :event_id, :latitude, :longitude 
#Relationship 
    belongs_to :customer 
    belongs_to :event 

的看法他這樣

<%= form_for(@event) do |f| %> 
    <div class="field"> 
    <%= f.label :title %><br /> 
    <%= f.text_field :title %> 
    </div> 
    <%= f.fields_for :locations do |e| %> 
    <%= e.hidden_field :longitude %> 
    <%= e.hidden_field :latitude %> 
    <% end %> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

控制器看起來像這樣

def new 
    @event = Event.new 
    @location = Location.new 
    ... 
    def create 
    @event = current_customer.events.build(params[:event]) 
    @event.locations.build(params[:locations]) 
    respond_to do |format| 
    ... 

問題是,當我創建事件時,會生成表單,它會創建事件並創建位置並與事件關聯,但我的經緯度字段爲空。我必須指出他們是float類型,但我不明白爲什麼它不應該工作

更新:我注意到,對我來說,能夠訪問field_for我必須改變field_for單

<%= f.fields_for :location do |e| %> 

但後來這樣做時,我在嘗試創建事件

Can't mass-assign protected attributes: location 

如果出現以下錯誤和params爲具有遵循

"location"=>{"longitude"=>"-80.9460917", 
"latitude"=>"46.4350391"} 

這是我的javascript

function getLocation() 
{ 
    if (navigator.geolocation) 
    { 
     navigator.geolocation.getCurrentPosition(showPosition); 
    } 
} 
    function showPosition(position) 
    { 
     document.getElementById('event_location_latitude').value=position.coords.latitude; 
     document.getElementById('event_location_longitude').value=position.coords.longitude; 
    } 

我承認它的醜陋,但它的application.js我與形式

<script type="text/javascript"> 
    getLocation(); 
    </script> 

的函數,而之前<%結束%稱爲它的工作>的形式

+0

經緯度是隱藏字段。你確定它的價值嗎?如果你從來沒有設置任何經度和緯度,它將是零。我沒有在代碼中看到它 –

+0

是的,它們是用javascript添加的,實際上它們沒有顯示出來,如果我將它更改爲文本字段更新的東西 – Jseb

+0

但它存儲在哪裏?會議?當你做一個隱藏的領域時,它應該從其他地方繼續。 –

回答

0

檢查了這一點。

http://railscasts.com/episodes/196-nested-model-form-revised

,如果你有看它以後的問題。讓我知道

在你隱藏的字段代碼中,你需要設置一個值。例如。

<%= f.hidden_field :song_id, value: params[:id] %> 
<%= f.hidden_field :paid_price, value: @song.price %> 
+0

我已經檢查過它,它同樣有我,但它不工作 – Jseb

+0

經度和緯度值得到通過,我顯示什麼通過 – Jseb

+0

在上面的例子。您從價值中獲取數據:@ song.price並將其保存到:paid_price。 –

0

你把:位置在你的attr_accessible? cz錯誤你表明是不能爲你的位置批量分配

+0

在事件模型中,我有這條線attr_accessible:customer_id,:description,:locations_attributes,並在我的位置我有這attr_accessible:地址,:customer_id,:event_id,:latitude,:longitude – Jseb

+0

你能試試嗎? ? accepted_nested_attributes_for:locations_attributes,:allow_destroy => true在你的事件模型中 – Nich

+0

獲取此錯誤未找到名稱爲'locations_attributes'的關聯。它已被定義? – Jseb