Search code examples
ruby-on-railsruby-on-rails-3viewmodel-associations

Retrieving data in ruby on rails through association


I have three tables Users(contains users details) users_shifts(contains users shift mapping) and shift(it's id is in users_shift table). What I'm doing is assigning multiple shifts to users and i want to retrieve all the data from users, users_shift and shift table. I have done the following thing :

In user model:

has_many :users_shifts, :dependent => :destroy

In users_shift model :

has_one :shift
belongs_to :user

In Shift Model

belongs_to :users_shift

In controller i have :

User.all

Now i want to fetch all the data in a table in view. I have to display users and his shift. Users detail will come from users table and shifts details will come from shifts table. Users_shift is used for users shift mapping.


Solution

  • try in your console first

    @user_shifts = @user.users_shifts # by using this you get all users_shifts details for that particular user.
    @shift = @user_shift.shift # by using this you will get shift for that paricular user_shift
    

    same way you can also

    @shift.user_shift # for getting details for users_shifts
    @user_shifts.user # for getting details about user