2013-03-22 60 views
0

我有兩個模型與相應的控制器和視圖:ProfileComment在一個視圖中顯示來自兩個模型的數據

我的應用程序的整個視圖(整個網頁)在Profileshow.html.erb。在此頁面上,用戶應該能夠創建評論,其中belongs_to a Profile

無需導航到標準/comments/new頁面即可完成此操作?

編輯: 繼軌指南後,我實現:

<%= simple_form_for([@profile, @profile.comment.build], html: {class: "form-inline"}) do |f| %> 
    <%= f.error_notification %> 

    <%= f.input :description, label: false, placeholder: 'Create an comment', input_html: { class: "span4" } %> 
    <%= f.submit 'Submit', class: 'btn btn-small'%> 

<% end %> 

CommentController

def create 
    @profile = profile.find(params[:profile_id]) 
    @comment = @profile.comments.create(params[:comment]) 
    redirect_to profile_path(@profile) 

而且我得到這個錯誤:

undefined method `comment' for #<Profile: 

固定:在構建聲明,需要的意見是多

@profile.comments.build 
+1

看看這個:http://guides.rubyonrails.org/getting_started.html#generating-a-controller – siekfried 2013-03-22 15:29:47

+0

請參閱上面的錯誤 – mnort9 2013-03-22 16:26:22

+0

你在表單聲明中忘記了's'註釋:'<% = simple_form_for([@ profile,@ profile.comments.build]' – siekfried 2013-03-22 19:09:51

回答

1

所有你需要做的就是添加評論表單代碼到配置文件#表演。然後在profile_controller的表演動作做這樣的事情:

def show 
@comment = Comment.new 
end 

而且在評論控制器添加:

def create 
@comment = Comment.create(params[:comment]) 
end 
+0

我相信你想說的第一種方法是在新的動作中,而不是show動作。 – GKnight 2015-10-06 19:27:42

0

你可能會考慮保存表單和更新使用AJAX調用,並可能像Knockout頁面。因此,在profiles/show.html.erb中,製作一個常規(單獨)表單來發布評論。使用jQuery或類似的東西通過AJAX將表單發佈到/ comments,所以它會在您的評論控制器中執行創建操作。讓該控制器返回一個JSON響應,該響應既可以是保存的註釋,也可以是類似於{:fieldname =>'too long'}的錯誤消息的散列。

在客戶端上,解析json響應並顯示保存的註釋,或者顯示錯誤消息,解釋爲什麼無法保存。你可以在普通的jQuery中完成所有這些工作,但添加Knockout之類的東西會使它更簡單一些。

相關問題