簡體   English   中英

在一個視圖中顯示兩個模型的數據

[英]Displaying data from two models in one view

我有兩個模型,分別帶有控制器和視圖: ProfileComment

我的應用程序的整個視圖(整個網頁)都在Profile show.html.erb 在此頁面上,用戶應能夠創建注釋,該注釋belongs_to Profile

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

編輯:遵循rails指南后,我實現了:

<%= 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

您需要做的就是將注釋表單代碼添加到profile#show中。 然后在profile_controller的show動作中執行以下操作:

def show
 @comment = Comment.new
end

在注釋控制器中添加:

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

您可能會考慮使用AJAX調用以及類似Knockout之類的方法來保存表單並更新頁面。 因此,在profile / show.html.erb中,制作一個常規(單獨)表格,僅用於發布評論。 使用jQuery或類似的東西通過AJAX將表單發布到/ comments,因此它將在您的注釋控制器中執行create動作。 讓該控制器返回JSON響應,該響應將是保存的注釋,或者是類似於{:fieldname =>'too long'}}的錯誤消息的哈希。

在客戶端上,解析json響應並顯示已保存的注釋,或顯示錯誤消息,說明無法保存該注釋的原因。 您可以使用普通的jQuery完成所有這些操作,但是添加類似Knockout的操作將使其變得更加簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM