Jose Jose - 10 months ago 20
Ruby Question

Accessing Attributes from different Model

I have two models in a has_many relationship:

  1. User
    (has_many :vacations)

  2. Vacation
    (belongs_to: user)

I am trying to display a User's credits attribute in the Vacation index view. How do I go about it?

I have tried:
<%= vacation.user.credits %>
, however, I am getting an error.

What are the right steps in doing so? Does it have anything to do with the Action Controller Parameters?

User Model

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :vacations

Vacation Model

class Vacation < ActiveRecord::Base
belongs_to :user
before_validation :calculate_days

def calculate_days
if from_date && to_date
self.leave_credit = from_date.business_days_until(to_date) + 1



One approach could be using the current_user method, since you're already using devise. This would work only if credits have to be displayed only to the currently logged in user, say in the dashboard. try using <%= current_user.credits %>

You could also try

class VacationsController < ApplicationController
  def index
    @user = User.find(params[:user_id])
    @credits = @user.credits

Another one line approach could be

@credits = User.find(params[:user_id]).credits