添加特定用户以查看页面上的内容

adding a specific user to see something on the page

我有一个简单的 rails 应用程序,我将用户分为角色 卖家客户,id 为 1 和 2分别。现在我希望 customers 在索引页面上看到与 sellers 不同的东西,为此我已经尝试过但没有任何反应。

        <div class="container-fluid">
    <div class="col-md-12 text-right">
        <% if role_id == 1 %>
            <%= link_to "Add a new Shipment", new_shipment_path, class: "btn btn-success" %>
    </div>
        <% else %>
            <% @shipments.each do |shipment| %>
        <div class="shipment">
        <h3><strong><%= shipment.user.full_name%></strong></h3>
        <h5><strong>DESCRIPTION: </strong><%= shipment.description %></h5>
         <div class="thumbnail">
        <td><%= image_tag shipment.image.url(:medium)%></td>
          <div class="meta">
            <%= link_to time_ago_in_words(shipment.created_at) + " ago" %> |
            <%= link_to "show", shipment %>
            <span class="admin"> 
              | <%= link_to "Edit", edit_shipment_path(shipment) %> |
              <%= link_to "Delete", shipment, method: :delete, data: { confirm: "Hey! Are you sure! You wanna delete this shipment??"} %>
          </span>
            </div>
          </div>
          <% end %>
        </div>
</div>
        <% end %>

我的seeds.rb

['seller', 'customer'].each do |role|
  Role.find_or_create_by({name: role})
end

您有两个错别字。它是 <% end %> 而不是 <% end -%>,它是 <% if role_id == "1" %>。注意 -= 而不是 %==.

确保正确嵌套所有内容也很重要,因为嵌套已完全关闭。您的 div 在 if-else 块的中间结束,而您过早地 end 您的 if-else 块。应该是这样的:

<div class="col-md-12 text-right">
    <% if role_id == 1 %>
        <%= link_to "Add a new Shipment", new_shipment_path, class: "btn btn-success" %>
    <% else %>
        <%= link_to "something else", class: "btn btn-success" %>
    <% end %>
</div>

我认为 find_or_create_by 已被弃用。而是使用 first_or_create.

['seller', 'customer'].each do |role|
    Role.where(name: role).first_or_create
end

另一对快速评论:

在 seller/customer 的控制器中有一个角色变量是更好的风格,例如user_role。这样更好,因为现在您比较的不是 ID,而是名称。这样你就可以做到 <% if user_role.name == "seller" %>.

如果您坚持使用 id 而不是名称,那么您应该将 id 视为整数,例如<% if role_id == 1 %>

编辑:我修改了我的嵌套示例以使用 == 1 而不是 = '1',并且我修正了一个拼写错误。

这个问题真的很麻烦,但我没有从任何地方得到帮助 我在 Whosebug 上又发布了一个关于这个问题的问题 然后这个谦虚的人@Rich peck 帮我解决了这个问题。