Search code examples
ruby-on-rails-4ormforeign-keysforeign-key-relationshipjoin

Rails has_many :through association: retrieve foreign attribute through foreign key


In our Rails app, there are 3 models:

class User < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :calendars, through: :administrations
end

class Administration < ActiveRecord::Base
  belongs_to :user
  belongs_to :calendar
end

class Calendar < ActiveRecord::Base
  has_many :administrations, dependent: :destroy
  has_many :users, through: :administrations
end

And here are the corresponding migrations:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email

      t.timestamps null: false
    end
  end
end

class CreateAdministrations < ActiveRecord::Migration
  def change
    create_table :administrations do |t|
      t.references :user, index: true, foreign_key: true
      t.references :calendar, index: true, foreign_key: true
      t.string :role

      t.timestamps null: false
    end
  end
end

class CreateCalendars < ActiveRecord::Migration
  def change
    create_table :calendars do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end

EDIT: here is also our UsersController:

class UsersController < ApplicationController
  before_action :logged_in_user, only: [:edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: [:index, :destroy]

  def index
    @users = User.paginate(page: params[:page], :per_page => 10)
  end

  def show
    @user = User.find(params[:id])
    @administrations = @user.administrations
    @calendar = current_user.calendars.build if logged_in?
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      @user.send_activation_email
      flash[:info] = "Please check your email to activate your account."
      redirect_to root_url
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to users_url
  end

  private

    def user_params
      params.require(:user).permit(:first_name, :last_name, :email,
                                    :password, :password_confirmation)
    end

    # Before filters

    # Confirms the correct user.
    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.try(:admin?)
    end

end

Once a user is logged in (authentication system already up and running), we want to display on his profile (users#show), all the calendars he has created.

We have seeded the database with the following instances:

User.create!(first_name:  "Andy") # This user's id is 1.

Calendar.create!(name: "CalendarA")

Calendar.create!(name: "CalendarB")

Calendar.create!(name: "CalendarC")

Administration.create!(user_id: 1, calendar_id: 1, role: "Creator")

Administration.create!(user_id: 1, calendar_id: 2, role: "Editor")

Administration.create!(user_id: 1, calendar_id: 3, role: "Viewer")

Then, we have created a _administration.html.erb partial:

<li id="administration-<%= administration.id %>">
  <span class="name"><%= administration.calendar_id %></span>
</li>

And included it in our user show.html.erb file:

<p><%= @user.first_name %>'s calendars</p>
<% if @user.administrations.any? %>
<%= render @administrations %>
<% end %>

And this is working, we get:

Andy's calendars:

  • 1
  • 2
  • 3

However, what we would like to get for each user, is not only the ids of his calendars, but their names too, like this:

Andy's calendars:

  • 1 CalendarA
  • 2 CalendarB
  • 3 CalendarC

So we tried to update the _administration.html.erb partial as follows:

<li id="administration-<%= administration.id %>">
  <span class="name"><%= administration.calendar_id.name %></span>
</li>

Which results in the following error:

NoMethodError in UsersController#show

undefined method `name' for 1:Fixnum

Application Trace | Framework Trace | Full Trace
app/views/administrations/_administration.html.erb:2:in `_app_views_administrations__administration_html_erb__2225316747000531998_70329866860100'
app/views/users/show.html.erb:32:in `_app_views_users_show_html_erb___891585127045041471_70329832995240'

How can we access the "foreign" attribute name from the calendar model through the foreign key calendar_id in the join administration model?


Solution

  • administration.calendar.name should work if your associations are set up correctly.

    Alternatively, you could add this method to Administration:

    def calendar_name
      calendar.name
    end
    

    and then just call administration.calendar_name