2017-02-19 48 views
0

我是Rails的新手,所以我将尝试并尽我所能解释这一点。在一个控制器中调用两个依赖于彼此的模型以查看视图

我有三个型号:艺人,巨星和festival_artist

艺术家只含有一个ID和这位演出
巨星只含有一个ID和一个festival_name
festival_artist包含一个ID,一个artist_id和festival_id

我使用脚手架创建了Fest,这是我的控制器和show.html.erb的地方。

下面是我的模型:

class Artist < ApplicationRecord 
    belongs_to :festival_artist 
end 

class Fest < ApplicationRecord 
    belongs_to :festival_artist 
end 

class FestivalArtist < ApplicationRecord 
    has_many :artists 
    has_many :fests 
end 

在我fests_controller.rb我:

def show 
    @festival_artists = FestivalArtist.where(festival_id: @fest.id) 
end 

我尝试添加:

def show 
    @festival_artists = FestivalArtist.where(festival_id: @fest.id) 
    @artists = Artist.where(id: @festival_artists.artist_id) 
end 

然而,抛出一个未定义的方法artist_id为#错误。

目标是在该艺术家所属艺术节的节日的show.html.erb页面中显示艺术家的名字。

在SQL这将是:

SELECT A.artist_name 
FROM festival_artists AS FA 
INNER JOIN artists AS A 
ON FA.artist_id = A.id 

有什么建议?甚至告诉我谷歌会帮助什么,因为我不确定我的术语是否正确。

让我知道你是否需要任何信息。

回答

2

猜你的模型结构不是100%正确的。请尝试查看http://guides.rubyonrails.org/association_basics.html了解详情。

有2种方式来处理你的Rails协会:

  1. HABTM(有属于多),因为注意到@grizzthedj答案。

  2. 的has_many:通过关联

在这种情况下,你的代码将看起来像

class Artist < ApplicationRecord 
    has_many :festival_artists 
    has_many :fests, through: :festival_artists 
end 

class Fest < ApplicationRecord 
    has_many :festival_artists 
    has_many :artists, through: :festival_artists 
end 

class FestivalArtist < ApplicationRecord 
    belongs_to :artists 
    belongs_to :fests 
end 

所以,你可以在控制器

def show 
    @festival_artists = @fest.artists 
end 
+0

谢谢!这工作。我不得不改变节日艺术家课堂,以使这些单数,但之后它的工作。我会更详细地阅读那篇文章。 – Austin

1

我不确定您是否需要FestivalArtist模型。如果在Artist和Fest模型中使用“has_and_belongs_to_many”,这将实现您正在寻找的多对多关系。

# fest.rb 
class Fest < ActiveRecord::Base 
    has_and_belongs_to_many :artists 
end 

# artist.rb 
class Artist < ActiveRecord::Base 
    has_and_belongs_to_many :fests 
end 
+0

访问艺术家,但如果艺术家模型没有festival_id,并且该模型没有artist_id,他们将如何连接? – Austin

+0

对。忘了那个。谢谢! – grizzthedj

相关问题