我有一个使用嵌套表单的 Rails 应用程序。详细信息如下,我尝试了这个解决方案(Rails 3 Nested Models unknown attribute Error),但由于某种原因,该字段重复多次,而不是正确列出和保存选项。在此先感谢您的帮助!
Newsavedmaps 的模型信息
has_many :waypoints, :dependent => :destroy
accepts_nested_attributes_for :waypoints
Newsavedmap_controller
def new
@newsavedmap = Newsavedmap.new
waypoint = @newsavedmap.waypoints.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @newsavedmap }
end
end
def edit
@newsavedmap = Newsavedmap.find(params[:id])
if @newsavedmap.itinerary.user_id == current_user.id
respond_to do |format|
format.html # edit.html.erb
format.xml { render :xml => @activity }
end
else
redirect_to '/'
end
end
地图视图
<% form_for @newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.error_messages %>
<% f.fields_for :waypoint do |w| %>
<%= w.select :waypointaddress, options_for_select(Waypoint.find(:all, :conditions => {:newsavedmap_id => params[:newsavedmap_id]}).collect {|wp| [wp.waypointaddress, wp.waypointaddress] }), {:include_blank => true}, {:multiple => true, :class => "mobile-waypoints-remove", :id =>"waypoints"} %>
<% end %>
<% end %>
当我使用上面的代码时,我的表单可以正常工作,但是提交它会给我这个错误:
UnknownAttributeError (unknown attribute: waypoint)
当我改变 ":waypoint do |w|" to ":waypoints do |w|" 在视图中,当用户创建新记录时,选择字段会消失,而在编辑视图中,选择字段会出现多次(无论用户在记录中保存了多少航点。)
我怎样才能让这个表单域正常工作?
编辑 1
这是我最近的尝试。对于新记录,选择字段不会出现。但是,在编辑视图中,选择字段会出现多次。这是一个 Rails 2 应用程序,仅供参考。从评论中得到提示,我使用了 collection_select 方法(不是 collection_for_select,因为我找不到相关文档。)再次感谢您的帮助!
<% f.fields_for :waypoints do |w| %>
<%= w.collection_select( :waypointaddress, @newsavedmap.waypoints, :waypointaddress, :waypointaddress, {:include_blank => true}, {:id =>"waypoints"} ) %>
<% end %>