外键(标识码)未填充的belongs_to的关联 [英] Foreign key (class_id) not populating in belongs_to association
问题描述
我是新来的铁轨和建设上rails3(BETA4)一个小的测试应用程序。
I'm new to rails and building a small test app on rails3 (beta4).
我使用的 Authlogic 以管理用户会话(安装在一个标准的方式按本教程)
I am using Authlogic to manage user sessions (setup in a standard fashion as per this tutorial)
我已经脚手架和安装卡模式(后基本),并设置了基本的活动记录关联的 belongs_to的
和的has_many
相关
I have scaffolded and setup a card model (a post basically), and set up the basic active record associations for a belongs_to
and has_many
relationship
user.rb
has_many :cards
card.rb
belongs_to :user
我说我的外键列到我的卡表: USER_ID
默认为 1
一切正常飞驰的。我已经做了我的意见,我可以看到的关联,卡可以属于不同的用户,这一切都太棒了。
Everything works fantastically. I've done my views and I can see the associations, card can belong to various users and it's all great.
但是我似乎无法创建新卡时抓住当前活动的用户
But I can not seem to grab the current active user when creating a new card
cards_controller.rb
def new
@card = Card.new
@card.user = current_user
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @card }
end
end
CURRENT_USER
在应用程序控制器定义,<一个href="http://github.com/binarylogic/authlogic_example/blob/5819a13477797d758cb6871f475ed1c54bf8a3a7/app/controllers/application_controller.rb"相对=nofollow>可以查看这里
current_user
is defined in the application controller, available to view here
USER_ID
正在通过 NULL
并没有被写入数据库 USER_ID
列,离开它默认为 1
,而不是实际登录的用户的ID。
user_id
is passing NULL
and nothing gets written to the database user_id
column, leaving it to default to 1
rather than the ID of actual signed in user.
我试着像 @user = CURRENT_USER
这可能是一些超级简单,但今天是我第一次真正的一天轨 - !谢谢
It's probably something super simple, but today is my first real day with rails - Thanks!
推荐答案
目前,它显示为您设置的新
操作的用户,但不是在创建
的行动。
Right now, it appears as you are setting the user on the new
action, but not on the create
action.
我看到两个选项,后者是更好的:
I see 2 options, the latter being the better:
-
如果你不断离开
@ card.user = CURRENT_USER
在新
动作可以设置一个隐藏的输入字段卡[user_ID的]
可包含当前用户的ID。这是因为任何人都可以随便扔任何他们想要进入这一领域完全坏主意。
If you continue to leave
@card.user = current_user
in yournew
action you can set a hidden input fieldcard[user_id]
which can contain the current user's id. This is a totally bad idea because anyone can just throw whatever they want into that field.
尝试移动 @ card.user = CURRENT_USER
在你的 @ card.save
前行权创建
的行动。这样,用户不能更动它,它会为它设置你的卡对象时,它实际上是即将被保存。
Try moving @card.user = current_user
right before your @card.save
line in the create
action. This way the user can't mess around with it, and it will set it to your card object when it's actually about to be saved.
这篇关于外键(标识码)未填充的belongs_to的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!