【发布时间】:2013-09-08 22:04:53
【问题描述】:
我有一个使用嵌套表单的 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 应用程序,仅供参考。从 cmets 获得启发,我使用了 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 %>
【问题讨论】:
-
第一件事。如果关联的名称是
waypoints,那么您必须使用f.fields_for :waypoints do |w|。当然,您没有名为waypoint的属性,因为这不是关联的名称。 -
现在您所说的“选择字段消失”到底是什么意思?这听起来不像是 Rails 问题。
-
谢谢,depa,但是当我这样做时,当用户创建新记录时,选择字段会消失,并且在编辑视图中,选择字段会出现多次(无论用户保存多少航点在记录中。)通过消失,我的意思是选择字段不会出现在新记录的源代码中或浏览器显示中。但是,它在编辑视图中出现了多次。再次感谢您的帮助!
-
是的,我读过它,如果你重复它并没有帮助,因为它第一次对我没有帮助。您是否使用 JavaScript 来创建新的选择或类似的东西?
-
另外,由于您在编辑视图中遇到问题,请在控制器中发布您的编辑操作内容。
标签: ruby-on-rails forms rails-activerecord ruby-on-rails-2