我开始学习rails并遇到问题。我正在写一个简单的应用程序(类似于我见过的twitter教程),用户登录并创建一个新帖子。保存登录用户的记录时,用户ID为NULL
当用户登录时,我设置的会话信息,所以,现在我已经登录的用户的ID如下
session[:id] = authorized_user.id
session[:email] = authorized_user.email
。登录后,用户被带到一种形式,他们可以提交新帖子(3个字段)。当用户点击提交时,我想用他们输入的数据创建一条新记录,并将该记录与该用户关联(用户ID)。我不确定如何做到这一点。
下面是控制器上的代码:
def create
#Used for creating new status posts
#Need to get the ID of the user logged in
@user = AdminUser.find(session[:id])
#Instantiate new object using form parameters
@post = Post.new(post_params)
@post.AdminUser = @user # THIS IS THE LINE NOT WORKING
#Save the object
if @post.save
#If save succeeds, redirect to the index action
flash[:notice] = "Status has been saved"
redirect_to(:action => 'index')
else
#If the save fails, redisplay the form so user can fix problems
render('new')
end
end
这里是post_params
def post_params
#Defining the params that are allowed to be passed with forms.
params.require(:post).permit(:post_status, :post_title, :post_content)
end
保存记录,但该记录的用户名是空的私有方法。
我的第一个尝试是试图通过UserID作为后置参数,但我认为这是一个潜在的安全风险,所以我试图找出一种替代方法。我相信这是简单的,我只是想念它。
您的'Post'模型中是否有'user_id'属性? – Pavan
发布模型admin_user和发布 – RSB
同时发布''提交''表单'时生成的'log'。 – Pavan