Search code examples
ruby-on-railsrubyruby-on-rails-4activerecordcontrollers

How to get assocated model's attribute values in views ? Rails


I have three models...

models/resident.rb

class Resident < ActiveRecord::Base
  belongs_to :hostel
  has_many :leaves,dependent: :delete_all
  has_one :user,dependent: :delete
end

models/user.rb

class User < ActiveRecord::Base
  belongs_to :resident
end

models/leave.rb

class Leave < ActiveRecord::Base
  belongs_to :resident
end

Now when I am trying to access the value of leave's attribute in views/leave/show.html.erb I am getting this:

app/views/leaves/show.html.erb

<%= @leaves %>

out put In Browser :

#<Leave::ActiveRecord_Associations_CollectionProxy:0x007fde611850f0> 

My leave controller looks like : leaves_controller.rb

class LeavesController < ApplicationController

  def new
    if logged_in?
       @leave=Leave.new
    else
      flash[:info]="Please login to mark a leave"
      redirect_to root_path
    end
  end
   def show
     @leaves= current_user.resident.leaves
   end

  def create
    @leave=current_user.resident.leaves.create(leave_params)
    if @leave.save
      flash[:info] = "Leave successfully marked"
      redirect_to new_leave_path
    else
      flash[:danger] = "Something wrong Happened try again"
      redirect_to root_path
    end
  end

  private
  def leave_params
    params.require(:leave).permit(:start_date,:end_date,:destination)
  end
end

Am I making correct leaves for resident and related user (create method)?

Is show method correct ?

and How to assess the user's leaves attribute in show.html.erb of leaves views.


Solution

  • A Resident has_many Leaves so current_resident.leaves returns an array of all the current_resident's leaves. You will need to loop through leaves to show individual attributes. Try

    @leaves.first.attribute_name 
    

    in your view to get an idea of how the data is represented. To show all the leaves you'll need to use a loop in the view

    @leaves.each do |leave|
      leave.inspect
    end