pranav prashant
pranav prashant

Reputation: 307

Linking two controllers in Rails

I have a signed in user profile and each profile has its own phone-book that no other user can access. The question is how should i implement it. Considering User as one controller and phone-book as another i'm not able to establish a relation between the two for a specific user login.

What should be my approach?

I have a sparate model for User and separate model for phone-book and have established a relation between them using has_many and belongs_to macro.

Upvotes: 2

Views: 1004

Answers (2)

Federico Toscano
Federico Toscano

Reputation: 101

Let's start with the models. You say that each User has only one PhoneBook so I would say that the right models should rather be:

class User < ActiveRecord::Base
    has_one :phone_book
end

class PhoneBook < ActiveRecord::Base
    belongs_to :user
end

Now, about the controllers. When you have a signed in User you will eventually have a "session thing" going on. Let's say you're using devise, then you will have a variable current_user that references the logged in user. So the PhoneBooksController will be something like:

class PhoneBooksController < ApplicationController    
  def index
    @phone_book = current_user.phone_book
  end   
end

Of course if your users can have more than one PhoneBook we go back to the has_many association:

class User < ActiveRecord::Base
    has_many :phone_book
end

class PhoneBook < ActiveRecord::Base
    belongs_to :user
end

and the controller becomes:

class PhoneBooksController < ApplicationController    
  def index
    @phone_books = current_user.phone_books
  end
  def show
    @phone_book = PhoneBook.find_by_id(params[:id])
  end
end

At last, if you want these phone books to be publicly readable I suggest you stick with a REST kind of URI

/phone_books/:id <-- good
/users/:id/phone_books/:phone_book_id <-- too complex

Hope I could help

Upvotes: 1

Domon
Domon

Reputation: 6823

You might want to place the page in /users/:user_id/phone_books/:id.

To achieve that,

You have to configure the paths in config/routes.rb:

resources :users do
  resources :phone_books
end

And in app/controllers/phone_books_controller.rb, find the user and their address book:

class PhoneBooksController < ApplicationController
  before_action :find_user

  def show
    @address_book = @user.address_books.find(params[:id])
  end

  private

  def find_user
    @user = User.find(params[:user_id])
  end
end

For more information about nested resources, please see the Getting Started with Rails guide.

Upvotes: 1

Related Questions