嵌套表单不更新数据库

时间:2011-09-29 12:23:01

标签: ruby-on-rails nested-forms

我有一个不更新数据库的嵌套表单。

型号:

用户:

has_many :designs, :dependent => :restrict

accepts_nested_attributes_for :designs

attr_accessible :designs_attributes

设计:

belongs_to :user

设计控制器:

def update
    @design = Design.find(params[:id])
    @user = User.find_by_id(@design.user_id)
    @points = (@user.points + 5000)
    if @design.update_attributes(params[:design])
        flash[:success] = "Design aproved"
        redirect_to designindex_path
    else
        @title = @design.name + %(, created by ) + @design.user.username
        render 'edit'
    end
end

以下是表格:

<%= form_for @user, :html => { :multipart => true } do |f| %>
    <%= f.hidden_field(:points, {:value => @points}) %>
    <%= f.fields_for :designs, @design do |d| %>
        <div class="field">
            <%= d.label :total_price, %(New price) %><br />
            <%= d.text_field :total_price %>
        </div>
        <%= d.hidden_field(:aproved, {:value => 1}) %>
    <% end %>
    <div class="actions">
        <%= f.submit "Submit" %>
    </div>
<% end %>

此外,当我按下Submit按钮时,它会将我重定向到root_path。

查看控制台输出,我发现了这个:

Started POST "/users/101" for 127.0.0.1 at 2011-09-29 15:31:16 +0200
Processing by UsersController#update as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"N16nb5i/PUPftGHs3uvnnLwrp8e/PQB88w0OU6DLGko=",
"user"=>{"points"=>"7500", "designs_attributes"=>{"0"=>{"total_price"=>"20",
"aproved"=>"1", "id"=>"66"}}}, "commit"=>"Submit", "id"=>"101"}

这里的问题似乎如下:

用户has_many设计,但在执行POST请求时,控制器未指定正在更新哪一个。无论如何,users.points属性既未更新。

更新

好的,我遇到了问题,我在users_controller.rb中有这个:

before_filter :authenticate, :only => [:index, :edit, :update, :destroy]
before_filter :correct_user, :only => [:edit, :update]

我正在尝试从管理员帐户更新其他用户的信息。我能以任何方式这样做吗?

以下是这些代码:

def correct_user
    @user = User.find(params[:id])
    redirect_to(root_path) unless current_user?(@user)
end

def current_user?(user)
    user == current_user
end

def authenticate
    deny_access unless signed_in?
end

def signed_in?
    !current_user.nil?
end

2 个答案:

答案 0 :(得分:0)

你想做的事:

<%= f.fields_for :designs, @design do |d| %>
  ...
<% end %>

这将确保它使用designs_attributes属性(我相信默认为0索引)。不记得你是否需要将@design包裹在一个数组([@design])中,不要相信你这样做。

你的参数应该看起来像{:user => {:designs_attributes => { '0' => {:id => 1, ... } } } }

答案 1 :(得分:0)

好的,让它工作,只修改了correct_user函数,如下所示

def correct_user
    @user = User.find(params[:id])
    redirect_to(root_path) unless current_user?(@user) || current_user.admin
end