0

User、Blog、Comment の 3 つのモデルがあります。

ユーザー.rb

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

ブログ.rb

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

コメント.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  

ここで、コメント テーブルの :user_id フィールドに current_user の ID を渡すにはどうすればよいですか。そのための隠しフィールドを作成できますが、安全ではありません。助けてください!前もって感謝します。

4

1 に答える 1

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 
于 2013-09-11T05:54:03.447 に答える