我想創建一個嵌套的表單欄,其中將同時創建兩個模型。該模型具有如下:創建兩個嵌套的模型
型號/活動
#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>
的函數,而之前<%結束%稱爲它的工作>的形式
經緯度是隱藏字段。你確定它的價值嗎?如果你從來沒有設置任何經度和緯度,它將是零。我沒有在代碼中看到它 –
是的,它們是用javascript添加的,實際上它們沒有顯示出來,如果我將它更改爲文本字段更新的東西 – Jseb
但它存儲在哪裏?會議?當你做一個隱藏的領域時,它應該從其他地方繼續。 –