我遇到的问题是在一对一的关系中使用两种模型播种数据库。
分贝/ seed.rb
auser = User.create!(email: "example@test.org",
password: "example",
password_confirmation: "example",
admin: true )
# profile_attributes: [name: "Example Test",
# street: "75 Barracks Rd",
# city: "Water,
# sex: "Male"]
# )
auser.profile.create!( name: "Example Test",
street: "75 Barracks Rd",
city: "Waterloo",
state: "AW",
zipcode: "23455",
#sex: "Male"
)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
street = Faker::Address.street_address
city = Faker::Address.city
state = Faker::Address.state_abbr
zipcode = Faker::Address.zip_code
password = "password"
n.User.create!(email: email,
password: password,
password_confirmation: password )
# profile_attributes: [name: name, sex: sex, street: street, city: city, state: state, zipcode: zipcode])
# n.profile.create!( name: name, street: street, city: city, state: state, zipcode: zipcode )
n.each { |user| user.profile.create( name: name, street: street, city: city, state: state, zipcode: zipcode) }
end
如果我在seed.rb文件中使用profile_attributes
作为注释,我会收到错误NoMethodError: undefined method "with_indifferent_access" for #<Array:0x86e46a0>
,但如果我按照当前的方式离开,我会收到错误SyntaxError: C:/Sites/NouveauMiniOlympics/db/seeds.rb:37: syntax error, unexpected '\n', expecting =>
**用户控制器中的用户参数**
def user_params
params.require(:user).permit(:id, :email, :password, :password_confirmation, profile_attributes: [:name, :street, :city, :state, :zipcode] )
end
答案 0 :(得分:1)
with_indifferent_access
是一个Rails ActiveSupport方法,它接受一个哈希并返回一个HashWithIndiffentAccess
,如果你使用符号或字符串来访问它的属性,它就不在乎了。
irb(main):002:0> hash = { foo: "bar" }
=> {:foo=>"bar"}
irb(main):003:0> hash["foo"]
=> nil
irb(main):004:0> hash.with_indifferent_access[:foo]
=> "bar"
irb(main):005:0>
那是什么意思? 当rails期望哈希时,你传入一个数组。
profile_attributes: [name: name, sex: sex, street: street, city: city, state: state, zipcode: zipcode]
最简单的解决方案是:
profile_attributes: { name: name, sex: sex, street: street, city: city, state: state, zipcode: zipcode }
但是如果我们只打算使用它们一次,我们真的不想输出所有这些变量!
99.times do |n|
User.create!(
email: Faker::Internet.safe_email, # "name@example.org"
password: 'password',
password_confirmation: 'password'
profile_attributes: {
name : Faker::Name.name,
street : Faker::Address.street_address,
city : Faker::Address.city,
state : Faker::Address.state_abbr,
zipcode : Faker::Address.zip_code
}
)
end