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



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

这是我的jokes#index:的erb

  <% @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中询问用户名的行中调用的。

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

@user = current_user.id

应该是什么时候:

@joke.user = current_user

新手失误。现在用户正在保存,其余的代码都能工作,因为这是实际的问题。

相关内容

最新更新