我有2个型号:
Performance and PerformanceType和2个相应的表:performance和performance_types。
在演出中有一个外键列“performance_type_id”。
如何使用ActiveRecord关联从其他表中获取performance_type_id的名称?
class Performance < ActiveRecord::Base
has_one :users
has_one :rates
has_one :performace_types
end
class PerformanceType < ActiveRecord::Base
belongs_to :performances
end
使用上面的代码我尝试进入控制台:
myvar = Performance.first
myvar.performance_types
NoMethodError: undefined method `performance_types' for #<Performance:0x007f9694b3e700>
我知道问题在于我对活跃记录关联的错误解释,有人可以帮助我吗?
问候。
从创建到外键的迁移添加...
class CreatePerformances < ActiveRecord::Migration
def change
create_table :performances do |t|
t.timestamps null: false
end
end
end
class CreatePerformanceTypes < ActiveRecord::Migration
def change
create_table :performance_types do |t|
t.timestamps null: false
end
end
end
class AddPerformanceTypeIdToPerformance < ActiveRecord::Migration
def change
add_column :performances, :performance_type_id, :integer
end
end
class AddAppointmentInfoToPerformance < ActiveRecord::Migration
def change
add_column :performances, :user_id, :integer
add_column :performances, :start_at, :datetime
add_column :performances, :end_at, :datetime
end
end
class AddUserToPerformances < ActiveRecord::Migration
def change
add_foreign_key :performances, :users
end
end
class AddTypeToPerformances < ActiveRecord::Migration
def change
add_foreign_key :performances, :performance_types
end
end
class AddAdditionalFieldsToPerformanceType < ActiveRecord::Migration
def change
add_column :performance_types, :name, :string
add_column :performance_types, :description, :string
end
end
class AddPerformanceTypeToRate < ActiveRecord::Migration
def change
add_foreign_key :rates, :performance_types
end
end
class AddRateToPerformances < ActiveRecord::Migration
def change
add_column :performances, :rate_id, :integer
add_foreign_key :performances, :rates
end
end
答案 0 :(得分:3)
has_one
和belongs_to
引用单个对象,因此您应该使用单一化形式
class Performance < ActiveRecord::Base
has_one :users
has_one :rates
has_one :performance_type
end
class PerformanceType < ActiveRecord::Base
belongs_to :performance
end
答案 1 :(得分:1)
我认为这就是你想要的。外键performance_type_id仍在演出中。您有许多具有相同性能类型的性能,但每个性能只有一种性能类型。
class Performance < ActiveRecord::Base
# note performance type is singular
belongs_to :performance_type
end
class PerformanceType < ActiveRecord::Base
has_many :performances
end
p = Performance.first
# this should work
p.performance_type
答案 2 :(得分:0)
您应该更改Performance类,列出与单数模型(不是复数)的“has_one”关系:
class Performance < ActiveRecord::Base
has_one :user
has_one :rate
has_one :performance_type
end
class PerformanceType < ActiveRecord::Base
belongs_to :performance
end
您的迁移文件也正确配置也很重要:
class CreatePerformances < ActiveRecord::Migration
def change
create_table :performances do |t|
end
create_table :performance_types do |t|
t.belongs_to :performance, index: true
t.belongs_to :rate
t.belongs_to :user
end
end
end