开发者

Ruby On rails accepts_nested_attributes_for simple question

开发者 https://www.devze.com 2023-02-12 14:32 出处:网络
Below is a simplified view of my two models User and Patient. A User has_one Patient and a Patient belongs_to a user.

Below is a simplified view of my two models User and Patient.

A User has_one Patient and a Patient belongs_to a user.

What I am trying to do in the rails console is:

p = Patient.new(:user_id => 2, :user_attributes => [{:username => 'patient'},{:password => 'password'}])

I get the error: NoMethodError: undefined method `with_indifferent_access' for [{:username=>"patient"}, {:password=>"password"}]:Array

What am I doing wrong?

Below are the two models:

# == Schema Information
#
# Table name: users
#
#  id                 :integer         not null, primary key
#  username           :string(255)
#  encrypted_password :string(255)
#  salt               :string(255)
#  active             :boolean
#  disabled           :boolean
#  last_login         :time
#  first_name         :string(255)
#  last_name          :string(255)
#  address1           :string(255)
#  address2           :string(255)
#  city               :string(255)
#  state              :string(255)
#  postcode           :string(255)
#  phone              :string(255)
#  cell               :string(255)
#  email              :str开发者_开发知识库ing(255)
#  created_at         :datetime
#  updated_at         :datetime
#
class User < ActiveRecord::Base
  has_one :patient

  attr_accessible :username, :password, :active, :disabled, :first_name, :last_name, 
  :address1, :address2, :city, :state, :postcode, :phone, :cell, :email
  attr_accessor :password

end

# == Schema Information
#
# Table name: patients
#
#  id         :integer         not null, primary key
#  user_id    :integer
#  created_at :datetime
#  updated_at :datetime
#

class Patient < ActiveRecord::Base
  belongs_to :user
  accepts_nested_attributes_for :user
  attr_accessible :user_id, :user_attributes
end


Try this instead (removing the array brackets, and keeping everything within one set of hash curly braces):

p = Patient.new(:user_id => 2, :user_attributes => {:username => 'patient' ,:password => 'password'})

However, I'm not sure why you're specifying a user_id and trying to create a new user too... maybe you just want this?

p = Patient.new(:user_attributes => {:username => 'patient', :password => 'password'})
0

精彩评论

暂无评论...
验证码 换一张
取 消