0

私はRORにかなり慣れていないので、現時点ではこの問題で立ち往生しています。

記事とテンプレートを使用してアプリケーションをセットアップしています。多くの記事を含むテンプレートを作成したいのですが、同じ記事を複数の異なるテンプレートに割り当てることができます。したがって、テンプレートを作成するときに記事を割り当てたいと思います。has_many アソシエーションを直接使用すると思うかもしれませんが、これは私の問題を把握しているとは思いません。

記事を複数のテンプレートに割り当てたいので、何らかのリンク テーブルを使用するとよいと思いました。

しかし、レールでそれを行う方法がわかりません!または、どのような解決策を探す必要がありますか。

この問題について私にアドバイスできる人はいますか?

4

3 に答える 3

2

リンク モデルの article_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

次に、モデルの article_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

リンクモデルとテーブルにいくつかの追加機能を直接追加できるため、これはベストプラクティスです。(これについての詳細はこちら

于 2012-04-28T21:14:09.317 に答える
1

has_and_belongs_to_manyの内容をチェックしてみてください

基本的に、コンソールに移動して入力します

$ rails g model article title:string body:text

$ rails g model template name:string some_other_attributes:type etc etc

$ 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
于 2012-04-28T20:48:51.657 に答える
1

has_and_belongs_to_many協会をお探しですか?

http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association

于 2012-04-28T20:42:36.273 に答える