简体   繁体   中英

How to Create an Associated Model Instance in Rails

My Rails 4 application has a User model which is generated by Devise GEM. And also it is associated with Profile model.

Here are the models:

class User < ActiveRecord::Base
  has_one :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

And DB Schema:

create_table "profiles", force: true do |t|
    t.string   "registered_city"
    t.integer  "user_id"
    ....
end

add_index "profiles", ["user_id"], name: "index_profiles_on_user_id"

create_table "users", force: true do |t|
  t.string   "email",                  default: "", null: false
  t.string   "encrypted_password",     default: "", null: false
  ....
end

add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

I want to create the associated Profile model instance for each/every User when they registered to the site.

For example, if a User completely registers for the site, a Profile model which belongs to that User should be created automatically and must be associated with related User. Also I need to fill their "registerd_city" field in Profile model, by default to "London".

How can I do this?

class User

  has_one :profile
  after_create :make_profile

  def make_profile
    create_profile(:registered_city => "London")
  end

end

Like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM