【问题标题】:Ruby on Rails: associationsRuby on Rails:关联
【发布时间】:2012-04-28 20:38:33
【问题描述】:

我对 ROR 还很陌生,所以我现在被这个问题困住了。

我正在设置一个包含文章和模板的应用程序。 我想创建包含许多文章的模板,并且可以将相同的文章分配给几个不同的模板。 因此,当您创建模板时,我想将文章分配给它。您会认为直接使用 has_many 关联,但我认为这不能解决我的问题。

我想将文章分配给多个模板,所以我认为在这里使用某种链接表就可以了。

但我不知道如何在 Rails 中做到这一点!或者我应该寻找什么样的解决方案。

有没有人可以为我解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord associations


    【解决方案1】:

    您可以创建链接模型articles_template

    rails generate model articles_template
    

    引用文章和模板

    class CreateArticlesTemplates < ActiveRecord::Migration
      def change
        create_table :articles_templates do |t|
          t.references :article
          t.references :template
          t.timestamps
        end
      end
    end
    

    然后在模型articles_template中设置关联

    class ArticlesTemplate < ActiveRecord::Base
      belongs_to :article
      belongs_to :template
    end
    
    class Article < ActiveRecord::Base
      has_many :articles_templates
      has_many :templates, :through => :articles_templates
    end
    
    class Template < ActiveRecord::Base 
      has_many :articles_templates
      has_many :articles, :through => articles_templates
    end
    

    恕我直言,这是最佳实践,因为您可以在链接模型和表中添加一些额外的功能。 (更多关于这个here

    【讨论】:

    • 这也是一个很好的解决问题的方法。最后,这真的取决于你是否需要有一些与两个模型的连接相关的状态。
    【解决方案2】:

    【讨论】:

      【解决方案3】:

      尝试在 has_and_belongs_to_many 上查看内容

      基本上,转到控制台并输入

      $ rails g 模型文章标题:字符串正文:文本

      $ rails g 模型模板名称:字符串 some_other_attributes:type 等

      $ rails g migration create_articles_templates

      然后编辑 create_articles_templates:

      class CreateArticlesTemplates < ActiveRecord::Migration
        def up
          create_table :articles_templates, :id => false do |t|
            t.integer :template_id, :article_id
          end
        end
      
        def down
        end
      end
      

      【讨论】:

        猜你喜欢
        • 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
        相关资源
        最近更新 更多