Patricio Jerí
Patricio Jerí

Reputation: 526

Setting a relationship between Users to access a resource

I'm teaching myself Rails and I'm trying to setup a collaboration relationship kind of like Github adds collaborators to projects. My models look like this:

class Restaurant < ActiveRecord::Base
    has_many :employees
    has_many :users, through: :employees
end

class User < ActiveRecord::Base
  has_many :employees
  has_many :restaurants, through: :employees
end

class Employee < ActiveRecord::Base
    belongs_to :restaurant
    belongs_to :user
end

The employee table also has a user_type column to handle permissions within the project (restaurant). I can't figure out how to make my employee_controller set this relationship. Users primary key is :email so I'm guessing a form should be able to receive the :email parameter, check if such a user with the inputed email exists, and add the relationship to the employees table.

I'm looking to be able to do something like this:

Restaurant_A = Restaurant.create(restaurant_params)
User_A.restaurants = Restaurant_A
Restaurant_A.employees = User_B

I think my models might be wrong but essentially I'd like to be able to have users with the ability to create a restaurant as well as be added as employees of another restaurant/their own restaurants.

Upvotes: 0

Views: 103

Answers (1)

Arslan Ali
Arslan Ali

Reputation: 17812

Your model is all right - no problem with that.

What you are trying to accomplish, you can accomplish that by following:

restaurant_a = Restaurant.create(restaurant_params)
# Remember to name it 'restaurant_a', it is convention in Ruby
user_a.restaurants << restaurant_a

<< is an operator that inserts left hand side thing into its right hand thing. So in our case, it will insert restaurant_a into the list of restaurants that are associated with user_a, and then you call save operation on your user_a like user_a.save.

Same case is on the other side:

restaurant_a.employees << user_b
# According to Ruby convention, you shouldn't start your variable
# name with an upper case letter, and you should user a convention
# called 'snake_type' naming convention. So instead of naming
# your variable like 'firstDifferentUser', name it 'first_different_user'
# instead.
restaurant_a.save # To successfully save the record in db

Edit:

For creating a form:

<%= form_for(@restaurant, @employee) do |f| %>
  <%= f.label :email %>
  <%= f.text_field :email %>
<% end %>

And you need to define @restaurant and @employee in your employee's controller new action, because you are gonna create a new employee for a particular restaurant.

Upvotes: 1

Related Questions