ternggio
ternggio

Reputation: 19

Rails association between User and Profile

I'm thinking creating a model User and Role. A user can create many roles they want to. After creating a role, a user can choose a role from the list and assign to himself. So, each role can have many users and a user is belong to a role. But this seems a bit weird because role should exist first. I'm not sure is this a correct way to establish relationship between User and Role because I want a user can edit a role, and apply to all the users.

If let's say, a user has_one role and a profile is belong_to the user, if the user wants to update the role, he needs to edit all the users one-by-one, which is waste of time. That's why I'm thinking a user can create as many roles as they want to, then they able to select a role from the list and assign to the user itself.

Here's the view:

<%= form_for(@user, remote: true) do |f| %>

<%= f.text_field :email, class: "form-control", autofocus: true, autocomplete: "off" %>
<%= f.check_box :admin, class:"checkbox" %>
<%= f.check_box :owner, class:"checkbox" %>

<%= f.fields_for :user_role do |ff| %>
<%= ff.collection_select :role_id, @roles, :id, :role_name, include_blank: false %>
<% end %>             

<%= f.button "Create",  class: "btn btn-success" %>

<% end %>

I'm not sure if my idea was a correct way to do, kindly advise. Thank you.

Upvotes: 0

Views: 489

Answers (2)

Mohamad Alhaj Rahmoun
Mohamad Alhaj Rahmoun

Reputation: 63

This can be a has_one :through relationship.

class User < ApplicationRecord
  has_one :user_role
  has_one :role, through: :user_role
end
class Role < ApplicationRecord
  has_one :user_role
  has_one :user, through: :user_role
end
class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

here, there User will be able to create as many roles as he wants. then you can link User to the Role he choose in the join table.

Upvotes: 1

Yunus Emre
Yunus Emre

Reputation: 419

Well, I think User and Role have a 1-to-N relationship. Users can create many roles but can assign only one of them to themselves. If you want to know "Who created that role?", roles can be belong to a user too. (You need to use something like has_one :role_creator, class_name: "User", foreign_key: "role_creator_id")

Upvotes: 0

Related Questions