Rails 怎么把 user_id 存进去。。。,新人求教

wxliuzifan · 2014年11月29日 · 最后由 cifery 回复于 2014年11月30日 · 2921 次阅读

comments_controller: def create @product = Product.find(params[:product_id])

@comment = @product.comments.create(comment_params) @comment.user_id = current_user.id redirect_to product_path(@product) end

comment——model class Comment < ActiveRecord::Base belongs_to :product
belongs_to :user validates :product_id, presence: true validates :content, presence: true, length: { maximum: 140 } end

现在数据库中有 product_id 和 user_id,product_id 能够存进去而 user_id 我不知道该怎么存进去。。。。

就像你说的这么存啊?

#2 楼 @hanluner 谢了啊。我还想问问@comment = @product.comments.create(comment_params) 和@comment.save有什么区别

#4 楼 @wxliuzifan 点不在这里,你只是把 user_id 赋值了,但是没有保存啊。create 创建的是 comment 对象,里面不包含 user_id。

#5 楼 @hanluner 这样的啊。。。

#4 楼 @wxliuzifan .create(params) 就等于 .new(params) and .save ,但你后面加入了 user_id,得再保存。建议在保存前就把 user_id 保存到 params 里面,这样就不用保存两次。

发帖请注意代码格式: 点这里点这里

需要 登录 后方可回复, 如果你还没有账号请 注册新账号