使用'update_attributes'到'has_many'更新数据库

时间:2011-09-16 15:10:32

标签: ruby-on-rails ruby-on-rails-3 has-many

我在获取第一个应用程序(我是一个新手)时遇到问题,以保存新的相关记录。我有两个模型(用户和图片)与has_many / belongs_to关联。我已经设置了userController,以便它可以创建一个新图片,如下所示:

  def new_picture
    @user = User.find(current_user.id)
    @picture = @user.pictures.build
  end

  def create_picture
    @user = User.find(params[:id])
    @picture = @user.pictures.build(params[:picture])
    if @picture.save
      flash[:notice] = "Your picture was successfully added."
      redirect_to :action => 'show', :id => @user.id
    else
      render :template => "new_picture"
    end
  end

我用

<%= link_to("add picture", :action => 'new_picture', :id => @user.id) if current_user %>

添加新的。但我也希望能够编辑。所以我用一些新代码更新了usercontroller:

  def edit_picture
    @user = User.find(current_user.id)
    @picture = @user.pictures.find(params[:id])
  end
  # When the user clicks the save button update record

  def update_picture
    @user = User.find(current_user.id)
    @picture = @user.pictures.find(params[:picture])
    respond_to do |format|
      if @picture.update_attributes(params[:picture])
        flash[:notice] = "Your picture was successfully updated."
        redirect_to :action => 'show', :id => @user.id
      else
        render :template => "new_picture"
      end
    end
  end

并添加了show.erb的编辑链接:

<%= link_to("edit picture", :action => 'edit_picture', :id => picture.id) if current_user %>

它加载编辑表单,数据全部都在正确的位置,但保存所有它正在做的是给我一个错误'在UsersController#update_picture中的ArgumentError'与我的图片表中的一堆未知密钥。

有人可以解释原因吗?我觉得这里有一块拼图我还不太明白......

提前致谢!

更新:查看代码如下:

<h1>New picture for <%= @user.name %></h1>
<% form_for :picture, @picture, :html => { :multipart => true }, :url => {:action => 'update_picture', :id => @user.id} do |f| %>

2 个答案:

答案 0 :(得分:1)

似乎无法在视图代码中看到您的问题,但是您可以作为嵌套路由更优雅地(RESTful)执行相同的操作。这样你就可以更清楚地看到问题了。

配置/ routes.rb中:

resources :users do
  member do
    resources :pictures
  end
end

应用程序/控制器/ pictures_controller.rb:

class PicturesController < ApplicationController
  before_filter :find_picture, :only => [:edit, :update]

  def edit
  end

  def update
    if @picture.update_attributes params[:picture]
      flash[:notice] = "Your picture was successfully updated."
      redirect_to user_path(current_user)
    else
      render :edit
    end
  end

  protected
  def find_picture
    @picture = current_user.pictures.find params[:id]
  end
end

应用程序/视图/图片/ edit.html.erb:

<%= form_for [current_user, @picture] do |f| %>
<!-- some stuff -->
<% end %>

并链接到您的编辑表单:

<%= link_to_if current_user, 'edit picture',
                edit_user_picture_path(:user => current_user, :id => picture) %>

答案 1 :(得分:0)

我建议将'accepts_nested_attributes_for:图片添加到用户模型,然后执行

<%= form_for @user do |form| %>
  .. user fields

  <%= form.fields_for :pictures do |picture_form| %> 

    .. picture fields

  <% end %>

  <%= form.submit %>
<% end %>
在视图中

另一种选择是为图片创建一个新的控制器。这可能更简单。