面对关联问题

时间:2013-09-11 05:45:22

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2 rails-models

我有三个模型User,Blog和Comment。

User.rb

class User < ActiveRecord::Base
  attr_accessible blah blah      
  has_many :blogs
  has_many :comments
end

Blog.rb

class Blog < ActiveRecord::Base
    attr_accessible :user_id, :title, :content
    belongs_to :user
    has_many :comments
end

Comment.rb

class Comment < ActiveRecord::Base
    attr_accessible :user_id, :blog_id, :comment
    belongs_to :blog
    belongs_to :user
end

在评论控制器的创建操作中

def create
    @blog = Blog.where('id=?', params[:blog_id])
    @comment = @blog.comments.new(params[:comment])
    @comment.save
end  

这里我将如何在comments表的:user_id字段中传递current_user的id,我可以为此创建一个隐藏字段,但它不安全。请帮忙!提前致谢。

1 个答案:

答案 0 :(得分:1)

这会做你想要的吗?

def create
  @blog = Blog.where('id=?', params[:blog_id])
  @comment = @blog.comments.new(params[:comment])
  @comment.user = current_user # force the user to be the logged-in user
  @comment.save
end