2012-10-19 33 views
0

我有一個典型的博客應用程序,用戶可以在帖子#show模板中發佈評論。發表評論從另一個控制器的顯示操作

resources :posts do 
  resources :comments 
end 

# posts_controller.rb 
def show 
    @post = Post.find(params[:id]) 
    @comment = @post.comments.build 
end 
# comments_controller.rb 
def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build(params[:comment]) 
    @comment.author = current_user 
    if @comment.save 
    redirect_to @post 
    else 
    render 'posts/show' 
    end 
end 

在視圖中,我首先檢查是否有評論,輸出它們,然後我顯示一個新的評論表單。

/ posts/show.html.slim 
- if @post.comments.any? 
    @post.comments.each do |comment| 
    p = comment.author.name 
... 
= form_for [@post, @comment] 

如果註釋驗證失敗,我會得到'無方法名稱爲nil類'錯誤。我認爲這是因爲@post.commets.any?返回true,因爲該評論是通過後關聯構建的 - 即使評論未通過驗證並且未保存。

你如何解決這個問題?

+0

試試@ post.comments.blank? – Ross

回答

3

當說明驗證失敗,comment.author可能沒有設置,因此將是零。這解釋了nil.name錯誤。

你可以嘗試像

@post.comments.each do |comment| 
    p = comment.author.try(:name) 

OR

@post.comments.each do |comment| 
    unless comment.new_record? 
    p = comment.author.try(:name) 
    end 
end 

OR

@post.comments.reject{|c| c.new_record?}.each do |comment| 
    p = comment.author.try(:name) 
end 
0

不知道你postscomments模型是什麼樣子,這是一個有點難以針點的問題,但在這裏我將如何解決你的問題:

# app/models/post.rb 
has_many :comments 

# app/models/comment.rb 
belongs_to :post 

# app/controllers/posts_controller.rb 
def show 
    @post = Post.find params[:id] 
end 

# app/controllers/comments_controller.rb 
def create 
    # No need to instantiate the post and build the comment on it here since 
    # we're going to set the post_id on the comment form. 

    @comment = Comment.new params[:comment] 
    if @comment.save 
    # ... 
    else 
    # ... 
    end 
end 

# app/views/posts/show.html.slim 
- if @post.comments.any? 
    @post.comments.each do |comment| 
    # ... 

- form_for Comment.new do |f| 
    = f.text_field :author 
    = f.text_field :body 
    # ... 
    = f.hidden_field :post_id, @post.id # This passes the comment's related post_id on to the controller. 
    = f.submit 

我不知道,如果斯利姆部分在語法上是正確的 - 我還沒有使用過模板引擎。

請注意,這不是生產安全的代碼!爲了保持這個例子的簡短和(希望),我省略了很多手續。

+0

感謝您的輸入。我已經知道這個問題是什麼。我正在努力尋找解決辦法。但是,通過將'post_id'作爲隱藏字段傳遞,您將使應用程序處於打開狀態。用戶可以更改隱藏字段併發布評論。 'user_id'同樣適用。 – Mohamad

1

變化

if @post.comments.any? 

if @post.comments.blank? 

,並再次檢查。

+0

這不會工作。 – Mohamad

相關問題