【问题标题】:Rails 3 HABTM one-linerRails 3 HABTM 单线
【发布时间】:2011-08-02 08:11:50
【问题描述】:

我需要一个单行器来生成一个 has_and_belongs_to_many 连接表,否则我将回到 Django 以获得更简单的多对多结构。

rails 3 生成模型 article_tags [..]

Models

# article.rb
has_many :articles_tags
has_many :tags, :through => :articles_tags

# tag.rb
has_many :articles_tags
has_many :articles, :through => :articles_tags

# article_tag.rb
belongs_to :tag
belongs_to :article

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 many-to-many model-associations has-and-belongs-to-many


    【解决方案1】:

    哦,等等哈哈,我想这可能会奏效:

    rails g model articles_tags article:references tag:references --no-id --no-timestamps
    

    我想知道是否有任何方法可以抑制模型文件的创建 (article_tags.rb),以便我可以使用标准的 has_and_belongs_to_many 语法而不必指定 :through 参数?我正在寻找终极单线:向任何可以改进上述单线以启用 仅使用 has_and_belongs_to_many 语法而不使用连接模型的人!否则,我将回到 Django,它是内置的 ManyToManyFields。

    【讨论】:

      【解决方案2】:

      听起来您正在寻找标准的 has_and_belongs_to_many:

      # article.rb
      has_and_belongs_to_many :tags
      
      # tag.rb
      has_and_belongs_to_many :articles
      

      您的连接表将被称为 articles_tags,并且只需要包含两列,article_idtag_id(不需要 id 列,因为它不是模型)。

      这是在Rails Guide to Associations 中。我强烈建议您熟悉 Rails 指南。

      对于生成器来说,这几乎太简单了。您只需要两个空模型类和连接表,它们将在迁移中定义,如下所示:

      def self.up
        create_table :articles_tags, :id => false do |t|
          t.integer :article_id
          t.integer :tag_id
        end
      end
      
      def self.down
        drop_table :articles_tags
      end
      

      【讨论】:

        【解决方案3】:

        不知道这么长时间后这是否仍然感兴趣,但我想你可以看看https://github.com/zealot128/ruby-habtm-generator:它是一个Rails 生成器,可以为HABTM 表生成正确的迁移。

        【讨论】:

          【解决方案4】:

          使用 generate 会创建两个索引

          查看这个答案https://stackoverflow.com/a/9825571/643500

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多