我有两个模型:用户和商店
class Store < ActiveRecord::Base
belongs_to :user
class User < ActiveRecord::Base
has_one :store
Schema looks like this:
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.string "encrypted_password"
t.string "salt"
t.boolean "admin", :default => false
t.string "username"
t.string "billing_id"
end
create_table "stores", :force => true do |t|
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.string "store_name"
t.integer "user_id"
end
用户必须登录才能通过输入“email”和“store_name”来注册商店。从stores_controller创建如下所示:
def create
@store = Store.new(params[:store])
if @store.save
@store.user_id = current_user.id
flash[:success] = "this store has been created"
redirect_to @store
else
@title = "store sign up"
render 'new'
end
end
在ApplicationsController中
def current_user
@current_user ||= user_from_remember_token
end
但是,当我签入数据库时,@ store.user_id = nil。由于某种原因,它无法将current_user.id放入@ store.user_id。任何人都能帮助检测为什么会这样?我以为我有正确实施的关联。感谢
答案 0 :(得分:2)
这种情况正在发生,因为您在保存后设置了@store.user_id
。
理想情况下,您应该使用关联构建器:
def new
@store = @current_user.store.build(params[:store])
有关这些的更多信息,请参阅"Association Basics"指南。