2011-06-25 68 views
2

這是我有我的模型定義了一個簡單的博客如何在rails中獲取帖子ID?

def User 
    has_many :comments, :dependent => :destroy 
    has_many :posts 
end 

def Post 
    belongs_to :user 
    has_many :comments 
end 

def Comment 
    belongs_to :user 
    belongs_to :post 
end 

在我的崗位控制器我有這樣的代碼,這樣我可以在創建視圖中的註釋

def show 
    @post = Post.find(params[:id]) 
    @comment = Comment.new 
    respond_to do |format| 
     format.html # show.html.erb 
     format.xml { render :xml => @post } 
    end 
    end 

然後我評論#創建我有這個

def create 
    @comment = current_user.comments.create(params[:comment]) 
    if @comment.save 
     redirect_to home_show_path 
    else 
     render 'new' 
    end 
    end 

我應該如何使我的評論模型可以接收post_id?我已經在我的Post show視圖中做了這個修復,但有沒有更好的方法?

<%= f.hidden_field :post_id, :value => @post.id %> 

回答

6

有沒有必要通過設置post_id通過啊idden字段 - 但是這意味着人們可能會將他們的評論與任何隨機帖子相關聯。

更好的方式可能是使用嵌套的資源來發布帖子的評論。要做到這一點,請在您的routes.rb文件中的以下內容:

resources :posts, :shallow => true do 
    resources :comments 
end 

那麼你的形式應該是這樣的:

<%= form_for @comment, :url => post_comments_path(@post) do %> 
    ... 
<% end %> 

這將意味着表單POST到路徑/post/[:post_id]/comments - 這意味着反過來該POST_ID是提供給控制器作爲PARAM:

def create 
    @comment = current_user.comments.new(params[:comment]) 
    @comment.post = Post.find(params[:post_id]) 
    if @comment.save 
     ... 
    end 
end 

這與使用的帖子ID做一個選擇了郵政的優勢,當t他找不到帖子,將會引發錯誤。

它也可能是值得重寫該控制器的方法略有下降,從而使Post.find至上:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.new(params[:comment]) 
    @comment.user = current_user 
    if @comment.save 
     ... 
    end 
end 

希望有所幫助。

+0

謝謝你,這幫了很多。我現在開始工作了。 – Kevin

2

是的,還有更好的辦法。按照official Routing guideGetting Started指南中的說明使用嵌套資源。入門指南甚至涵蓋了帖子和評論的確切例子!

+0

感謝您的文章,我會讀到這一點。 – Kevin

1
<%= form_for :comment, :url => post_comments_path(@post) do |f| %> 

<%= f.text_field :content %> 
<%= f.submit%> 
<% end %> 

在您的評論創建行動你有

def create 
@post = Post.find(params[:post_id]) 
@comment = @post.comments.build(params[:comment]) 
@comment.user = current_user #if you are using devise or any authentication plugin or you define a current_user helper method 
if @comment.save 
...... 
end 

如果你正在使用的軌道3,在你的config/routes.rb中做

resources :posts do 
resources :comments 
end 

代碼的第一部分應在你的文章/ show.html.erb

+0

謝謝你,這是我需要的 – Kevin