且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ActiveRecord模型复杂的关联

更新时间:2023-12-01 13:16:16

协会被设计成可读的和可写的。他们的价值有很大一部分是你可以做这样的事情:

Associations are designed to be readable and writable. A large part of their value is that you can do something like this:

@band.gigs << Gig.new(:venue => @venue)

这听起来,不过,像你想的是只读的东西。换句话说,要场地和流派联系在一起,但你永远不会做的:

It sounds, though, like you want something that's read-only. In other words, you want to associate Venues and Genres, but you'd never do:

@venue.genres << Genre.new("post-punk")

,因为这没有任何意义。 A点只有一个类型,如果一个频段,具有特定的类型有千兆那里。

because it wouldn't make sense. A Venue only has a Genre if a Band with that particular Genre has a Gig there.

协会不为工作,因为他们必须是可写的。下面是我会怎么做只读协会:

Associations don't work for that because they have to be writable. Here's how I'd do readonly associations:

class Genre
  has_many :bands 

  def gigs
    Gig.find(:all, :include => 'bands', 
             :conditions => ["band.genre_id = ?", self.id])
  end

  def venues 
    Venue.find(:all, :include => {:gigs => :band}, 
      :conditions => ["band.genre_id = ?", self.id])
  end
end