我无法通过外键访问相关模型的属性。
每个用户有许多应用程序每个应用程序属于一所学校
当我尝试在用户仪表板 (user#show) 中显示 school_name 属性时,我收到 school_name 的未定义方法错误
该应用程序有一个 user_id 和一个 school_id,它们应该用作外键。我在想这可能有问题,但找不到文档。
我可以调用@application.school_id,它会返回正确的整数值,但学校表上的相关属性是无法恢复的。
任何帮助将非常感激。
用户控制器
class UsersController < ApplicationController
before_filter :authenticate_user!
def show
@user = current_user
@applications = @user.applications :include => [:school_name]
end
end
用户模型
class User < 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 => :applications
has_and_belongs_to_many :schools
end
用户/show.html.erb
<div class="hero-unit">
<center><h1> Hello <%= @user.name %></h1></center>
<%= link_to "New Application", new_application_path %>
<h2>
Current Applications
</h2>
<%@applications.each do |app|%>
<%= app.school_name %>
<%end%>
</div>
应用模型
require 'carrierwave'
class Application < ActiveRecord::Base
mount_uploader :app_file, ImageUploader
belongs_to :user, :class_name => User, :foreign_key => "user_id"
belongs_to :school, :class_name => School, :foreign_key => "school_id"
belongs_to :editor
end