为什么这个选择字段在我的Rails表单中多次出现?

时间:2013-09-08 22:04:54

标签: ruby-on-rails forms rails-activerecord ruby-on-rails-2

我有一个使用嵌套表单的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

Maptry View

<% 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 %>

1 个答案:

答案 0 :(得分:0)

您的表单存在以下问题。

  1. 使用f.fields_for :waypoints,因为参数需要与关联名称匹配。
  2. 使用collection_select而不是select,因为您在该字段后面有一个ActiveRecord模型。
  3. 因此,考虑到这一点,您可以尝试使用此表单:

    <% form_for @newsavedmap, :html => { :id => 'createaMap' } do |f| %>
      <%= f.error_messages %>
      <% f.fields_for :waypoints do |w| %>
        <%= w.collection_for_select :waypoint, :waypointaddress, @newsavedmap.waypoints, :waypointaddress, :waypointaddress, { :include_blank => true }, { :multiple => true, :class => "mobile-waypoints-remove", :id =>"waypoints" } %>
      <% end %>
    <% end %>
    

    collection_select的API有点难以理解。我通常也需要几次尝试。之前的SO问题可能有助于澄清问题:Can someone explain collection_select to me in clear, simple terms?