我正在開發一個簡單的博客應用程序,並且無法顯示與評論相關的用戶名。Rails應用程序 - Object_ID返回用戶名
評論belongs_to:帖子和:用戶。帖子belongs_to:用戶和has_many:評論。用戶has_many:帖子和:評論。
的創建我的意見樣板工程措施和與POST_ID和USER_ID預計存儲評論:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
@comment.user = current_user
if @comment.save
redirect_to @post
else
flash.now[:danger] = "error"
end
end
private
def comment_params
params.require(:comment).permit(:content)
end
end
我能夠通過控制檯訪問的用戶名與Comment.first.user預期.name,它返回用戶名。當試圖做到這一點的看法,我得到以下錯誤:
undefined method `name' for nil:NilClass
這裏是視圖:
<% @post.comments.each do |comment| %>
<p>User:<%= comment.user.name %></p>
<p>Comment:<%= comment.content %></p>
<% end %>
當我在查看用戶刪除.name和應用程序顯示什麼看起來是object_id。
User:#<User:0x00000001f62830>
Comment:Test comment
我已嘗試重置這裏提到的數據庫:Show username when posting comments in Rails
我也嘗試解決這裏提到的proxy_id:Returning issue in Comment::ActiveRecord_Associations_Collection
我不知道什麼嘗試。此外,當我重新設置意見表,以便在它裏面沒有數據,應用程序仍顯示:
User:
Comment:
當它遍歷即使在它裏面沒有數據。我認爲它與ID混淆的動態查找器有關,但我試着將它移動到控制器,如這裏所述,retrieving username with find_by_id(comment.user_id).name not working,我仍然遇到未定義的方法錯誤。有任何想法嗎?欣賞洞察力。我沒有使用評論寶石,正在開發cloud9,並且正在使用PostgreSQL。
所以你確定數據庫中的所有評論都有用戶?在控制檯中檢查它。也許你有一個評論沒有用戶,它墜毀。刷新數據庫,創建一條評論,檢查控制檯,而不是視圖。 – denys281
我正在使用delete_all方法清除數據庫。我確認沒有記錄存在,然後使用該應用程序創建記錄,並獲取no方法錯誤。我認爲它與任何數據之前存在的某種proxy_id綁定,但我無法弄清楚。我應該用什麼其他方法來刷新數據庫? –
這很奇怪,@ denys281。當我爲每個循環添加限制時,名稱方法的工作原理如下:<%@ post.comments(1..1000).each do | comment | %>。數據庫中只有六條記錄。如果我刪除1..1000,名稱方法出錯。有任何想法嗎? –