Reputation: 197
I'm having issues seeding a database with two models i a one to one relationship.
db/seed.rb
auser = User.create!(email: "[email protected]",
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
If i use profile_attributes
as commented out in the seed.rb file, i get the error NoMethodError: undefined method "with_indifferent_access" for #<Array:0x86e46a0>
but if i leave it the way it currently is, i get the error SyntaxError: C:/Sites/NouveauMiniOlympics/db/seeds.rb:37: syntax error, unexpected '\n', expecting =>
**user params in user controller **
def user_params
params.require(:user).permit(:id, :email, :password, :password_confirmation, profile_attributes: [:name, :street, :city, :state, :zipcode] )
end
Upvotes: 1
Views: 418
Reputation: 102055
with_indifferent_access
is a Rails ActiveSupport method which takes a hash and returns a HashWithIndiffentAccess
which put simply does not care if you use symbols or strings to access its properties.
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>
So what does this mean? You are passing in an array when rails expects a hash.
profile_attributes: [name: name, sex: sex, street: street, city: city, state: state, zipcode: zipcode]
simplest solution is:
profile_attributes: { name: name, sex: sex, street: street, city: city, state: state, zipcode: zipcode }
But we don't really want to type all of those variables out if we are only going to use them once!
99.times do |n|
User.create!(
email: Faker::Internet.safe_email, # "[email protected]"
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
Upvotes: 1