在索引页面(Rails)上显示资源作者/所有者

时间:2016-08-01 00:16:19

标签: ruby-on-rails

我正在尝试在Joke页面上显示该笑话文本下方jokes#index的作者姓名,但我做错了。 User has_many jokesjoke belongs_toUser

这是我的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的行中调用此错误,询问用户的姓名。

1 个答案:

答案 0 :(得分:0)

原来用户是nil,因为在我的控制器中我有:

@user = current_user.id

应该是:

@joke.user = current_user

菜鸟错误。现在用户正在保存并且其余代码正常工作,因为这是实际问题。

相关问题