ruby-on-rails - Rails:ActiveSupport::HashWithIndifferentAccess:Class 的未定义方法 `primary_key'

标签 ruby-on-rails

我的 User 模型有一个多态关系。我正在使用设计。

当我尝试编辑用户的详细信息时,出现以下错误:

undefined method `primary_key' for ActiveSupport::HashWithIndifferentAccess:Class

通过表单提交的数据为:
{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"Ap0JP2bs/w9J6iI9rZahiKR1K8UEIi7rp33a4OutMbo=",
 "user"=>{"email"=>"some_email@yahoo.com",
 "rolable"=>{"first_name"=>"Cristian",
 "last_name"=>"Gavrila",
 "city"=>"16"}},
 "commit"=>"Update"}

Controller 方法是:
  def update
    @user = User.find(current_user.id)

    if @user.update_attributes(params[:user])
      redirect_to edit_user_registration_path, notice: 'Your profile was successfully updated.'
    else
      redirect_to edit_user_registration_path, error: "Something went wrong, couldn't update your profile!."
    end
  end

型号:

1.用户
class User < ActiveRecord::Base
  belongs_to :rolable, :polymorphic => true

  # Devise business
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :remote_avatar_url, :avatar, :login, :username, :email, :password, :password_confirmation, :remember_me

  # For authenticating with facebook
  attr_accessible :provider, :uid, :rolable
  devise :omniauthable, :omniauth_providers => [:facebook]

  # For authenticating with both username or email
  attr_accessor :login

  # Upload avatar
  mount_uploader :avatar, AvatarUploader

  # Makes username necessary
  validates :username, :presence => true
end

2. 客户
class Customer < ActiveRecord::Base
  has_one :user, :as => :rolable
  has_one :preferences, :class_name => "CustomerPreferences"
  belongs_to :city

  attr_accessible :first_name, :last_name
end

有什么问题?

最佳答案

根据您的请求哈希,您正在传递 rolable属性为:

"rolable"=>{"first_name"=>"Cristian",
           "last_name"=>"Gavrila",
           "city"=>"16"}

您不能这样做,除非您指定 User模型接受 rolable 的嵌套属性.但是,您已经设置了 User作为属于Rolable而不是反过来。嵌套属性并非旨在处理这种反向关系 - 您可能需要重新考虑您在此处尝试完成的任务,并相应地修改关系。

例如,你可能想把你的散列翻过来并传递 rolable带有 user 的属性内嵌的属性。或者您可能想转 rolable进入 has_one 关联。

关于ruby-on-rails - Rails:ActiveSupport::HashWithIndifferentAccess:Class 的未定义方法 `primary_key',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17278038/

相关文章:

javascript - Rails 选择表单 : displaying and using select form value before submit?

ruby-on-rails - 在 chrome 中通过 Ruby on Rails 播放 MP3

mysql - 将数据库中的值设置为 False 取决于其他值 True/False

ruby-on-rails - 环境变量返回 nil

ruby-on-rails - ruby rails : Editor for backend of the web application

ruby-on-rails - 在初始化时设置 default_url_options

ruby-on-rails - 使用 Capistrano 运行同步或异步任务

ruby-on-rails - Rails 可选的 gem 配置

ruby-on-rails - 带排序的自定义分页,Rails 3

mysql - rake 问题 - 无法加载 mysql2 库