创建属于各自微博客和用户的评论(在使用Devise的应用程序中)



现在,我有两个模型:User和Micropost。用户模型正在使用Devise。

相关文件示例:

user_controller.html.erb:

class PagesController < ApplicationController
  def index
    @user = current_user
    @microposts = @user.microposts
  end
end

index.html.erb:

<h2>Pages index</h2>
<p>email <%= @user.email %></p>
<p>microposts <%= render @microposts %></p>

microposts/_micropost.html.erb

<p><%= micropost.content %></p>

micropost.rb:

class Micropost < ActiveRecord::Base
  attr_accessible :content
  belongs_to :user
end

user.rg:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
  has_many :microposts
end

现在我想为微柱创建评论:

  • 每个评论都应该属于各自的微博客和用户(评论者)。不确定如何做到这一点(使用多态关联是一个好情况吗?)
  • 一个用户应该有很多微帖子和评论(也不知道如何合作)
  • 我不知道如何让评论成为当前登录的用户(我想我必须对Devise的current_user做点什么)

有什么建议可以做到这一点吗?(对不起,我是Rails初学者)

不,您所说的一切都不表明您需要多态关联。您需要的是一个带有如下模式的注释模型:

    create_table :comments do |t|
        t.text :comment, :null => false
        t.references :microposts
        t.references :user
        t.timestamps
    end

然后

# user.rb
has_many :microposts
has_many :comments
# microposts.rb
has_many :comments

你可能会想要你的评论嵌套路由。所以,在你的routes.rb中,你会有类似的东西

#routes.rb
resources :microposts do
    resources :comments
end

在您的comments控制器中,是的,您将分配comment.user的值,如下所示。。。

# comments_controller.rb
def create
    @comment = Comment.new(params[:comment])
    @comment.user = current_user
    @comment.save ....
end

您可能想看看《Beginning Rails 3》一书,它将带您了解这一点。

相关内容

最新更新