【问题标题】:adding a specific roles to user to see something on the page向用户添加特定角色以查看页面上的内容
【发布时间】:2015-12-16 10:10:51
【问题描述】:

虽然我之前有过这个问题,但没有得到任何有用的东西并且被卡住了。好的,我的应用程序是一个简单的 ebay 克隆,我将用户划分为角色 id 为 1 和 2 的买家和卖家。当任何人注册或登录时,他们将被转移到应用程序的索引页面,现在我希望买家看到一些东西与索引页面上的卖家不同,为此我尝试了 if 和 else 方法,但什么也没发生。做错什么了吗? 我还有其他方法可以解决这个问题。

我的 Index.html.erb 文件

    <div class="col-md-12 text-right">
        <% if role_id == 1 %>
            <%= link_to "Add a new Product", new_product_path, class: "btn btn-success" %>
    </div>
    <% else %>
      <div class="col-md-8">
        <% @products.each do |productt| %>
    <div class="product">
    <h4><strong><font style="text-transform: capitalize;"><%= shipment.user.full_name%></strong></h4></font>
    <h5><strong>DESCRIPTION: </strong><%= product.description %></h5>
     <div class="thumbnail">
    <td><%= image_tag product.image.url(:medium)%></td>
      <div class="meta">
        <%= link_to time_ago_in_words(product.created_at) + " ago" %>
        <span class="admin"> 
          | <%= link_to "Show Details", product %>
       </span>
     </div>
    </div>
   </div>
  </div>
 <% end %>
<% end %>

我的种子.rb

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

【问题讨论】:

  • 如何识别用户是买家还是卖家?您需要将每个用户与角色相关联,以确定该用户是买家还是卖家。
  • 嘿 @nayiaw 我是 Rails 新手,你能告诉我该怎么做吗

标签: ruby-on-rails if-statement roles


【解决方案1】:

你需要多学习一点关于系统结构的知识。具体来说,您是在询问如何将买家/卖家发送到不同的页面(这表明存在主要的系统分歧),而我认为您实际上是在询问 authorization

  • 授权 = 授予用户做某事的权限
  • 身份验证 = 他们是用户吗?

我认为您应该有一个基本级别的用户(没有“角色”),能够为每个用户分配特定的授权能力。

这基本上会让每个用户成为买家,除了那些拥有许可销售的用户。这样,您可以为您的用户分配一个“级别”,如果他们在数据集中具有该级别,则允许他们进行操作。

--

我会这样设置:

#app/models/user.rb
class User < ActiveRecord::Base
   # columns id | username | password | role_id | etc
   belongs_to :role
   def has_role? test_role
       role.id == test_role
   end
end

#app/models/role.rb
class Role < ActiveRecord::Base
   # columns id | name | description | etc
   has_many :users
end

这将使您能够调用以下内容:

<%= link_to "Add a new Product", new_product_path, class: "btn btn-success" if current_user.has_role? "1" %>

这将使您能够将一系列角色添加到您的Role 模型中,并为每个用户分配一个角色。这将定义用户可以访问的功能数量(即他们只能在“2”级等情况下销售)。

【讨论】:

    猜你喜欢
    • 2015-12-14
    • 2018-01-06
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多