2012-01-27 48 views
0

现在,我有两种模型:User和Micropost。用户模型使用Devise。文件的创建属于它们各自的微博和用户的评论(在使用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> 

微柱/ _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初学者)

回答

2

不,你说的没有什么建议你需要多态关联。你需要的是一个comments模型与模式类似如下:

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 

..并在您的意见控制器,是的,你分配的comment.user类似下面的值...

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

你可能想看看Beginning Rails 3书,它会引导你阅读这本书。

相关问题