我不知道如何最好地说这个。如果有人认为他们可以做得更好,那就是我的客人:)
我正在尝试做一些有些困难的事情。我有一个名为User的设计模型,用户有很多地址。当用户注册时,我希望他们必须放入一个地址,并使用当前用户的user_id
将地址添加到数据库中。
现在我正在尝试使用cocoon完成此操作,但我无法弄清楚如何使其首先创建用户,然后使用刚创建的用户的user_id
创建地址。
如果有帮助,这就是我的表格:
以下是schema.rb
create_table "addresses", force: :cascade do |t|
t.integer "user_id"
t.string "line_one", default: "", null: false
t.string "line_two", default: ""
t.integer "apartment"
t.string "city", null: false
t.string "state", null: false
t.integer "zip", null: false
t.string "address_type", default: "residential", null: false
t.boolean "default", default: true, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "addresses", ["user_id"], name: "index_addresses_on_user_id", using: :btree
create_table "users", force: :cascade do |t|
t.string "username", default: "", null: false
t.string "email", default: "", null: false
t.string "first_name", default: "", null: false
t.string "middle_initial", default: ""
t.string "last_name", default: "", null: false
t.integer "profile_pic_id", default: 0
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :username, presence: true, uniqueness: { case_sensitive: false }
attr_accessor :login
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions.to_h).first
end
end
has_many :auctions, dependent: :destroy
has_many :addresses, dependent: :destroy
end
地址模型:
class Address < ActiveRecord::Base
belongs_to :user
end
如果您还有其他需要,请告诉我们!
答案 0 :(得分:1)
使用accepts_nested_attributes_for可以通过父级保存相关记录。
因此,在您的情况下,您可以与用户一起保存与用户记录关联的多个地址。
例如,用户模型就像
Read in the first word;
if it is "print" then read in the rest of the line and print it;
if it is "foo" read in the next 3 words as aprameters and call bar();
然后在创建记录时,您可以将地址记录与用户记录一起保存。
class User < ActiveRecord::Base
has_many :addresses, dependent: :destroy
accepts_nested_attributes_for :addresses
end