[英]nested attribute pagination error (kaminari)
我很確定這是一個簡單的修復程序,但我沒有看到它。 我有一個要在其中顯示音樂視頻評論的應用程序。 以下是我的控制器:
def show
@music_video = MusicVideo.find(params[:id])
@comment = Comment.new
@comments = @music_video.comments.page(params[:page]).per(3)
end
上面是我的音樂視頻控制器。
def create
@music_video = MusicVideo.find(params[:music_video_id])
@comment = @music_video.comments.build(comment_params)
if @comment.save
flash[:notice] = "Comment Submitted"
redirect_to music_video_path(@music_video)
else
render 'music_videos/show'
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to root_path, notice: "Comment Deleted"
end
private
def comment_params
params.require(:comment).permit(:body)
end
以上是我的評論控制器
最后是我的表演頁面:
<div class="comments_row">
<% @music_video.comments.each do |comment| %>
<% if user_signed_in? && current_user.admin? %>
<p class="comment"><%= comment.body %></p>
<%= link_to 'Delete Comment', music_video_comment_path(@music_video,comment),
method: :delete %>
<% else %>
<p class="comment"><%= comment.body %></p>
<% end %>
<%end%>
</div>
<%= paginate @comments %>
我很確定控制器有問題,但是我不確定它到底是什么。 @comments在正確的CRUD操作(顯示)中的正確控制器(MusicVideo)中。 目前,我在特定的顯示頁面上有六個評論,分頁顯示的很好,但是六個評論沒有分頁。 有什么想法嗎?
編輯 - - - - - - -
我發現了一個問題,但偶然發現了一個新問題。 我發現在我的控制器中,我聲明@comments =分頁等。在我看來,沒有@comments要分頁。 現在的問題是,當我使用
<%= paginate @comment %>
代碼會中斷。我現在遇到的問題是要分頁的變量。 嘗試此代碼也會中斷
<%= paginate @music_video.comments %>
有什么建議嗎?
我使用kaminari gem進行分頁,設置了一個測試應用程序。 這是我的音樂視頻控制器的表演動作如下所示:
def show
@music_video = MusicVideo.find(params[:id])
@comments = @music_video.comments.page(params[:page]).per(3)
end
這是我的表演視圖:
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong> <%= @music_video.name %>
</p>
<% @comments.each do |comment| %>
<p>
Comment: <%= comment.text %>
</p>
<% end %>
<%= paginate @comments %>
<%= link_to 'Edit', edit_music_video_path(@music_video) %> |
<%= link_to 'Back', music_videos_path %>
它正在工作,分頁正在向我顯示。
我認為我直接看到的一件事是,您應該使用<% @comments.each do |comment| %>
<% @comments.each do |comment| %>
而不是<% @music_video.comments.each do |comment| %>
<% @music_video.comments.each do |comment| %>
因為您現在擁有它的方式將顯示該視頻的所有評論,而不管您在哪個頁面上。 如果您有6條評論並希望每頁3條,您將看到兩頁的分頁,因為您正在基於@comments
運行分頁,而最終您會在兩頁上看到全部6條評論,因為您正在執行.each
都有@music_videos.comments.each
。
因此,至少在兩個地方都使用@comments
是一個開始。 並確保您使用<%= paginate @comments %>
進行分頁。 如果您在控制器中使用它並查看得到了什么? 您有沒有評論?
另外,瑞安·貝茨(Ryan Bates)還在卡米納里(Kaminari)上進行了出色的轉播: http ://railscasts.com/episodes/254-pagination-with-kaminari(該網站是解決Rails問題的好資源)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.