Rails has_one 和 Belongs_to 帮助
我有两个模型:用户和商店
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
用户必须登录才能通过输入“电子邮件”和“商店名称”来注册商店。从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 中。任何人都可以帮助检测为什么会这样吗?我以为我已经正确实施了关联。谢谢
I have two models: User and Store
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
User must login in order to sign up a store by inputting "email" and "store_name". create from stores_controller looks like this:
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
In ApplicationsController
def current_user
@current_user ||= user_from_remember_token
end
However, when I check in the database, @store.user_id = nil. For some reason, it's not able to put in current_user.id into @store.user_id. Anybody able to help in detecting why this might be? I thought I had associations correctly implemented. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为您在保存后设置了
@store.user_id
。理想情况下,您应该为此使用关联构建器:
有关这些的更多信息可以在“关联基础知识”中找到 指南。
This is happening because you're setting the
@store.user_id
AFTER saving it.Ideally, you should be using the association builder for this:
More information about these can be found in the "Association Basics" guide.