我正在尝试创建一个嵌套的表单轨道,其中将同时创建两个模型。该模型如下:
模型/活动
#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|
...
问题在于,当我创建事件时,会生成表单,它会创建事件并创建位置并与事件关联,但我的经度和纬度字段为空。我必须注意它们是浮动类型,但我不明白它为什么不起作用
更新:我注意到我能够访问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>
在&lt;%end%&gt;之前形式
答案 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 %>
答案 1 :(得分:0)