2012-01-27 46 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書,它會引導你閱讀這本書。

相關問題