2016-08-01 70 views
0

我想在我的jokes#index頁面上顯示該笑話文本下Joke作者的名字,但是我做錯了什麼。 A Userhas_manyjokesjokebelongs_to a User顯示資源在索引頁上的作者/所有者(Rails)

下面是我的jokes#index再培訓局:

<% @jokes.each do |joke| %> 
    <h2 id="joke-title" style="margin-top: 50px"> 
     <%= joke.title %> 
     <% if joke.kids == true %> 
     <%= image_tag 'icon_kids_green.jpg', style: "height: 25px; margin-left: 10px" %> 
     <% end %> 
     <% if joke.mixed == true %> 
     <%= image_tag 'icon_mixed_purple.jpg', style: "height: 25px; margin-left: 10px" %> 
     <% end %> 
    </h2> 
    <p id="joke-body"><%= joke.body %></p> 
    <p><strong>Submitted by: <%= User.find(joke.user).first_name %></strong></p> 
    <% if current_user.admin && joke.approved == nil && joke.rejected == nil %> 
     <%#= link_to do %> 
     <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>Approve Joke 
     <%# end %> 
     <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>Reject Joke 
    <% end %> 
    <% if current_user == joke.user || current_user.admin %> 
     <%= link_to edit_joke_path(joke) do %> 
     <span style="color: blue" class="glyphicon glyphicon-pencil" aria-hidden="true"></span><span style="color: blue">Edit Joke</span> 
     <% end %> 
     <%= link_to joke_path(joke), data: {:confirm => 'Are you sure?'}, :method => :delete do %> 
     <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>Delete Joke 
     <% end %> 
    <% end %> 
    <% end %> 

這裏是我的jokes_controller索引定義:

def index 
    @jokes = Joke.all 
    end 

我覺得這應該是一個相當簡單的問,所以我必須做的事情非常愚蠢。我得到的錯誤信息是:

Couldn't find User with 'id'= 

這個錯誤被稱爲在我erb線來回詢問用戶名。

+0

看來你的'joke.user_id'是零。你能提供一下'joke.inspect'的輸出嗎? – retgoat

+0

@retgoat,'joke.inspect'產生這樣的結果:''#<笑話id:4,標題:\「計算牧羊犬\」,身體:\「在一個說話的牧羊犬得到了所有的綿羊...... \ ,孩子:真,混:真,批:無,被拒絕:無,user_id:無,created_at:\「2016-07-31 23:18:15 \」,updated_at:\「2016-07-31 23:18 :15 \「>」' – Liz

回答

0

原來的用戶是nil,因爲在我的控制器我有:

@user = current_user.id 

當它應該是:

@joke.user = current_user 

新手的錯誤。現在用戶正在保存,其餘的代碼工作,因爲這是真正的問題。

+0

你也不需要做'User.find(@ joke.user)'。除非用戶失去了自己:) –

+0

@MattW,這是一個非常現實的可能性......但我會改變它。大聲笑... – Liz

相關問題