1

各位开发者您好!最近我一直在玩 Rails 3.0,经过相当多的研究,我有点卡住了。我想知道在我的情况下哪种方法或解决方案是最好的(我还没有找到答案)。所以我想要实现的是简单而直接的。

我想做这样的事情:

class User < ActiveRecord::Base
    has_many :feeds
    has_many :casts, :through => :feeds
end

class Feed < ActiveRecord::Base
  has_many :users
  has_many :casts
end

class Cast < ActiveRecord::Base
  belongs_to :feed
end

所以最后我需要有像 User.first.feeds 这样的方法来获取所有用户的提要和 User.first.casts 来通过他/她的提要获取所有用户的演员表。拥有 Feed.first.casts 和 Feed.first.users 也很不错。很简单,对,但我也很难为我想要实现的目标创建迁移。

我知道上面的代码不起作用——我一直在玩它,所以这只是我想要实现的概念。

基本上我的问题是:我应该以某种方式通过连接模型还是使用范围?(你也可以提供一个代码片段)以及我该如何进行迁移?

谢谢,很抱歉,我在网上找不到关于这个简单案例的太多信息。

编辑:用户和 Feed 上的 has_and_belongs_to_many 在我的情况下不起作用,因为它不允许我拥有 @user.casts,它只提供 @user.feeds 和 @feed.users

4

2 回答 2

2

您想要的是用户和 Feed 之间的多对多关系。

您需要在代码中使用类似的内容,以使 User 和 Feed 关系正常工作。

class User < ActiveRecord::Base
  has_and_belongs_to_many :feeds
end

class Feed < ActiveRecord::Base
  has_and_belongs_to_many :users
end

您可以在 Rails 指南中阅读更多相关信息 - http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association

如果您愿意,您可能还想查看使用 has_many :through 和中间模型(在此处解释http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many)喜欢为用户提要关系记录存储任何元数据。

编辑:我设法在 3.0 和 3.1 上获得了类似的设置(使用 has_many :through)。

这是我的模型的内容。

➜  app  cat app/models/*
class Cast < ActiveRecord::Base
  belongs_to :feed
end

class Feed < ActiveRecord::Base
  has_many :subscriptions
  has_many :casts
end

class Subscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :feed
end

class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :feeds, :through => :subscriptions

  # For 3.1
  has_many :casts, :through => :feeds
  # For 3.0
  def casts
    Cast.joins(:feed => :subscriptions).where("subscriptions.user_id" => self.id)
  end
end

这是我使用的迁移

➜  app  cat db/migrate/*
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end
class CreateFeeds < ActiveRecord::Migration
  def self.up
    create_table :feeds do |t|
      t.string :name

      t.timestamps
    end
  end

  def self.down
    drop_table :feeds
  end
end
class CreateCasts < ActiveRecord::Migration
  def self.up
    create_table :casts do |t|
      t.string :name
      t.integer :feed_id

      t.timestamps
    end
  end

  def self.down
    drop_table :casts
  end
end
class CreateSubscriptions < ActiveRecord::Migration
  def self.up
    create_table :subscriptions do |t|
      t.integer :feed_id
      t.integer :user_id
    end
  end

  def self.down
    drop_table :subscriptions
  end
end
于 2011-06-11T21:51:35.063 回答
0

http://railscasts.com/episodes/265-rails-3-1-overview中,Ryan Bates 说 rails 3.1 支持链式 has_many :through 调用。这在 3.0 中是不可能的

于 2011-06-11T23:17:30.410 回答