我有一个连接两个模型的连接表: 一组 和位置(实际上是地址表中的地址ID)。此连接表称为Group_Locations
class Provider < ActiveRecord::Base
has_and_belongs_to_many :groups
belongs_to :designation
belongs_to :specialty
has_many :provider_locations
has_many :invoices
has_many :groups, through: :provider_locations
end
class ProviderLocation < ActiveRecord::Base
belongs_to :provider
belongs_to :group_location
end
class Group < ActiveRecord::Base
#validations
validates :group_name, presence: true
#associations
has_many :providers
has_many :invoices
has_one :billing
has_many :group_locations
end
我的另一个模特很棒:
class GroupLocation < ActiveRecord::Base
belongs_to :address
belongs_to :group
has_many :provider_locations
end
和地址:
class Address < ActiveRecord::Base
has_many :group_locations
has_many :billings
end
所有这些关联,我可以写一个不错的测试:
require 'test_helper'
class GroupLocationTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "adding a group and an address" do
group = Group.new
group.group_name = 'MyGroup'
group.save
adr = Address.new
adr.city = 'Las Cruces'
adr.state = 'New Mexico'
adr.zip = '88012'
adr.address_line_one = '382 Dark side of moon'
adr.address_line_two = ''
adr.save
gl = GroupLocation.new
gl.group = group
gl.address=adr
assert gl.save, 'Group location did not save'
puts gl.group.group_name
end
end
编辑::::感谢Daiku的帮助,但我有两个其他模型(Provider和ProviderLocation),现在我想要给定提供者名称的地址和组名。
他们的关系是一个名为ProviderLocation的连接表,其中包含group_location标识和provider_id。所以我不确定他们的关联(另一个我确定)我需要了解它...我的提供者模型中有:
has_many :groups, through: :group_locations
在尝试使用时,这没有给我一个错误:
puts Provider.where(first_name: "Shane").first.groups.first.group_name
1) Error: ProviderLocationTest#test_adding_a_provider_to_a_group_location: NoMethodError: undefined method `klass' for nil:NilClass test/models/provider_location_test.rb:37:in `block in <class:ProviderLocationTest>'
答案 0 :(得分:1)
在您的群组模型中,添加关联:
has_many :addresses, through: :group_locations
然后你可以:
Group.where(group_name: "MyGroup").first.addresses.first