adding a specific roles to user to see something o

2019-08-27 13:09发布

问题:

although i had this question before but did not get anything useful and am stuck. Ok my app is a simple ebay clone, where i had divided users into roles buyers and sellers with role id 1 and 2. When anyone sign up or login they are transferred to the index page of the app, Now i want buyers to see something different then sellers on the index page and for that I had tried the if and else method but nothing happened. Is am doing anything wrong? I there any other way to get on this.

My Index.html.erb file

    <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 %>

and

My seeds.rb

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

回答1:

You need to study a little bit more about system structure. Specifically, you're asking how to send a buyer/seller to different pages (which indicates a major system divide), whereas I think you're really asking about authorization.

  • Authorization = giving a user permission to do something
  • Authentication = are they a user at all?

I think you should have a base level user (no "roles"), with the ability to assign specific authorization ability to each user.

This will basically make every user a buyer, except for ones who have permission to sell. This way, you can assign a "level" to your users, allowing them actions if they have that level in their dataset.

--

I would have it set up like this:

#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

This will give you the ability to call the following:

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

This will give you the ability to add a series of roles to your Role model, allocating one to each user. This will define the amount of functionality that user will have access to (IE they can only sell if they are at level "2" etc).