如何在rails 3.1.3中以1对多的方式使用fields_for进行子更新?

时间:2012-02-16 03:01:06

标签: ruby-on-rails ruby-on-rails-3.1

用户拥有许多user_levels,user_level属于用户。以下是user_level for update的代码:

<%= simple_form_for @user do |f| %>
  <% @user.user_levels.each do |level| %>    
    <%= f.fields_for :user_levels, level do |builder| %>
      <p><%= render :partial => 'user_levels', :locals => {:f => builder, :i_id => level.position} %></p>  
    <% end %> 
  <% end %>
<% end %>

上面的代码将显示当前user_level并将所选设置设置为当前位置。问题是没有为user_level保存更新。

这是user_levels partial

<div class="fields">
  <%= f.input :position, :collection => return_position, :prompt => "Choose position", 
                      :label => false, :include_blank => true, :selected => i_id %>
  <%= link_to_remove_fields "remove", f %>
</div>

这是为params [:user]发布到服务器的字符串。用户目前有两个职位,一个职位被删除为更新:

{"name"=>"test eng", "login"=>"tester12", "password"=>"password", "password_confirmation"=>"password", "user_type"=>"employee", "user_levels_attributes"=>{"0"=>{"id"=>"5"}, "1"=>{"position"=>"elec_eng", "_destroy"=>"false", "id"=>"6"}}}

儿童更新的任何解决方案?非常感谢

更新:

  def new
    @user = User.new
  end

  def create
    @user = User.new(params[:user])
    @user.input_by_id = session[:user_id]
    if @user.save!
      redirect_to URI.escape("/view_handler?index=0&msg=saved!")
    else
      flash.now[:error] = 'not saved!'
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    @user.input_by_id = session[:user_id]
    if @user.update_attributes(params[:user])
      redirect_to URI.escape("/view_handler?index=0&msg=saved}")
    else
      flash.now[:error] = 'not saved!'
      render 'edit'
    end
  end

user.rb:

  has_many :user_levels, :dependent => :destroy
  accepts_nested_attributes_for :user_levels, :reject_if => lambda { |a| a[:position].blank? }, :allow_destroy => true
  validates_associated :user_levels

1 个答案:

答案 0 :(得分:1)

尝试删除行@user.user_levels.each do |level|,然后发布弹出的问题。 用户模型是否接受用户级别的嵌套属性?