Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing another table's attributes with a foreign key and belongs_to association
    primarykey
    data
    text
    <p>I am having trouble accessing an a related model's attributes by a foreign key. </p> <p>Each user has many applications Each application belongs to one school </p> <p>When I try to show the school_name attribute in the users dashboard (user#show), I get a undefined method error for school_name</p> <p>The application has a user_id and a school_id, which should serve as foreign keys. I was thinking there might be a problem with this, but couldn't find documentation. </p> <p>I can call @application.school_id and it will return the correct integer value, but related attributes on the school table are irretrievable.</p> <p>Any help would be much appreciated.</p> <p>Users controller</p> <pre><code>class UsersController &lt; ApplicationController before_filter :authenticate_user! def show @user = current_user @applications = @user.applications :include =&gt; [:school_name] end end </code></pre> <p>User Model</p> <pre><code>class User &lt; ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable has_many :applications has_many :editors, :through =&gt; :applications has_and_belongs_to_many :schools end </code></pre> <p>User/show.html.erb</p> <pre><code>&lt;div class="hero-unit"&gt; &lt;center&gt;&lt;h1&gt; Hello &lt;%= @user.name %&gt;&lt;/h1&gt;&lt;/center&gt; &lt;%= link_to "New Application", new_application_path %&gt; &lt;h2&gt; Current Applications &lt;/h2&gt; &lt;%@applications.each do |app|%&gt; &lt;%= app.school_name %&gt; &lt;%end%&gt; &lt;/div&gt; </code></pre> <p>Application Model</p> <pre><code>require 'carrierwave' class Application &lt; ActiveRecord::Base mount_uploader :app_file, ImageUploader belongs_to :user, :class_name =&gt; User, :foreign_key =&gt; "user_id" belongs_to :school, :class_name =&gt; School, :foreign_key =&gt; "school_id" belongs_to :editor end </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload