【问题标题】:Rails 3.2: nested_attributes and has_one association, in two differents formsRails 3.2:nested_attributes 和 has_one 关联,有两种不同的形式
【发布时间】:2012-11-23 05:40:54
【问题描述】:

我在 has_one 关联模型上使用了accepts_nested_attributes_for。

我有两个模型,一个用户和一个配置文件。一个用户有一个个人资料:

class User < ActiveRecord::Base
  attr_accessible :name, :email,:profile_attributes
  has_one :profile
  accepts_nested_attributes_for :profile
end

class Profile < ActiveRecord::Base
  attr_accessible :avatar
  belongs_to :user
  mount_uploader :avatar, AvatarUploader
end

我在编辑用户页面上有两个表单。一个更新主要用户属性(并且工作正常,下面未显示),然后是允许用户上传头像的一个:

<%= form_for @user, :html => {id: 'avatar_form' ,:multipart => true } do |f| %>
  <%= f.fields_for :profile do |builder| %>
  <%= builder.file_field :avatar %>
  <% end %>
  <%= f.submit %>
<% end %>

此提交不起作用,我收到此错误消息:

UsersController#update 中的 NoMethodError

nil:NilClass 的未定义方法“名称”

我的 UsersController 更新代码是:

def update
  @user = current_user
  if @user.update_attributes(params[:user])
    redirect_to home_path
  else
    render 'edit'
  end
end

参数是:

{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"YTpGnj9uIpybDAgf4c6pxMydY15ga5GZ++FBMe/6dV4=",
"user"=>{"profile_attributes"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x2303e08 @original_filename="test.jpg",
@content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"user[profile_attributes][avatar]\";  filename=\"test.jpg\"\r\nContent-Type: image/jpeg\r\n",
"id"=>"3"}},
"commit"=>"Upload",
"id"=>"1"}

任何帮助将不胜感激。谢谢!!

【问题讨论】:

  • 您的用户登录了吗?我的意思是如果current_user 为 nil,您将收到此错误消息 - 所以当没有使用登录时这将无法工作
  • 是的,用户已登录,我有 before_filter :signed_in_user,只有:[:home, :update, :edit]
  • 解决了!我在 tmp 文件夹中遇到了一些授权问题,将其更改为 def cache_dir "#{Rails.root}/tmp/uploads" end

标签: ruby-on-rails ruby ruby-on-rails-3.2 nested-attributes form-for


【解决方案1】:

添加到您的用户控制器

def new
  @user = User.new
  @user.profile.build
  #or
  #@user.build_profile

end

为了更好地了解正在发生的事情,请尝试将 gem "better_errors" 添加到您的 Gemfile 中

gem "better_errors"

你会得到一个控制台,你可以在里面输入

@user

作为输出,您将得到(nil 或 obj)。如果为零,您肯定会在新动作中伪造这条线

@user = User.new

如果您将 divise 用于自动。支持,像这里一样重写控制器 Override devise registrations controller

【讨论】:

    【解决方案2】:

    @安德烈 至于 has_one 关系, @user.profile.build 不起作用,需要选择下面的,@user.build_profile 有人告诉我如下: "如果关联是使用has_one定义的,我们使用"build_association"函数。对于has_many,它应该是"association.build"。

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多