2015-06-21 71 views
1

我在我的桌子上敲我的頭試圖找出爲什麼評論發佈comment.body,但是當我進入IRB body = nil,它不會顯示應用展示頁面。嵌套評論正文不被保存Ruby on Rails

結構:應用程序在其顯示頁面上有許多評論,同時還有評論表單。

Apps中查看:

<h3>Comments</h3> 
<% @comments.each do |comment| %> 
    <div> 
    <p><%= comment.user.email %></p> 
    <p><%= comment.body %></p> 
    <p><%= link_to 'Delete', [@app, comment], method: :delete, data: { confirm: 'Are you sure?' } %></p> 
    </div> 
<% end %> 
<%= render 'comments/form' %> 

評論控制器:

def create 
    @app = App.find(params[:app_id]) 
    @comment = current_user.comments.build(params[:comment_params]) 
    @comment.user = current_user 
    @comment.app = @app  
    @comment.save 

     if @comment.save 
     flash[:notice] = "Comment was added to the #{@comment.app.name}." 
     redirect_to(@app) 
     else 
     flash[:error] = "There was a problem adding the comment." 
     redirect_to(@app) 
     end 
    end 

def comment_params 
    params.require(:comment).permit(:user_id, :app_id, :body, :user_attributes => [:email]) 
end 

我的應用程序控制器:

def show 
    @app = App.find(params[:id]) 
    @comments = @app.comments.all 
    @comment = @app.comments.build 
    end 

def app_params 
    params.require(:app).permit(:name, :brief, :description, :element, :user_attributes => [:id], :element_attributes => [:name], :elements => [:name]) 
end 

評論形式:

<%= form_for [@app, @comment] do |f| %> 

    <div class="field"> 
    <%= f.label :body %><br> 
    <%= f.text_area :body %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
    <%= f.hidden_field :app_id %> 
<% end %> 

見鬼,爲什麼在服務器發佈,但不節能的身體嗎?我在這裏忽略了什麼?

在此先感謝。

+0

你的意思是說你在rails控制檯中做過'comment.body'嗎? – max

+0

@maxcal在IRB中,我查了一條評論,看到服務器的控制檯通過'Comment.find()'發佈了'body'的值,並返回了'body = nil',這意味着即使rails服務器發佈身體,顯然它從未得救過。 – Nickdb93

+0

'@comment = current_user.comments.build(params [:comment_params])'這行是否行? –

回答

1

根本不需要在這種情況下使用嵌套屬性。沒有理由通過表格傳遞user_idapp_id,因爲它們在控制器中是已知的。這樣做只是爲潛在的惡作劇打開了大門。像發送

user_id: 1, body: 'My boss is such a duchebag' 

哎呦。

def create 
    @app = App.find(params[:app_id]) 
    @comment = Comment.new(comment_params.merge(
    app: @app, 
    user: current_user 
)) 
    # notice that you where calling @comment.save twice.. 
    if @comment.save 
    flash[:notice] = "Comment was added to the #{@comment.app.name}." 
    redirect_to(@app) 
    else 
    flash[:error] = "There was a problem adding the comment." 
    redirect_to(@app) 
    end 
end 

def comment_params 
    params.require(:comment).permit(:body) 
end 
+0

你能指點我到一個地方,我可以更多地瞭解你做了什麼'(comment_params.merge( app:@app, user:current_user ))'?我從未在 – Nickdb93

+0

之前看到過,它只是[Hash.merge](http://ruby-doc.org/core-2.2.0/Hash.html#method-i-merge) – max

+0

'{a:1}。合併(b:2) - > {a:1,b:2}' – max