如何在rails控制台中使用关联测试/添加数据

时间:2014-04-16 14:39:44

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

我是rails初学者,我在Rails控制台中测试模型关联时遇到了一些麻烦。我知道这是一个简单的修复,但是,我不确定我是否创建了适当的模型,或者生成了正确的迁移,因此我将在此问题中包含此信息。

我已经阅读过rails文档(http://guides.rubyonrails.org/active_record_basics.htmlhttp://api.rubyonrails.org/),我知道答案就在那里,但我担心我缺乏经验会妨碍我完全最大化可用文档。

我需要能够在rails控制台

中创建has_many :categories, through: :article_categories的文章

以下是article,article_categories和category

的模型
class Article < ActiveRecord::Base
belongs_to :user
has_many :article_categories
has_many :categories, through: :article_categories
validates :title, presence: true
validates :content, presence: true
validates :categories, presence: true
  end

class ArticleCategory < ActiveRecord::Base
belongs_to :article
belongs_to :category
 end

class Category < ActiveRecord::Base
has_many :article_categories
has_many :articles, through: :article_categories
validates :names, presence: true

 end

以下是生成的主要迁移

Class CreateArticles < ActiveRecord::Migration
  def change
   create_table :articles do |t|
   t.string :title
   t.text :context
 end
end

class CreateArticleCategories < ActiveRecord::Migration
    def change
      create_table :article_categories do |t|
      t.belongs_to :article
      t.belongs_to :category
     t.timestamps
   end
  end
end

class CreateCategories < ActiveRecord::Migration

    def change
      create_table :categories do |t|
       t.string :name

      t.timestamps
    end
  end
 end

所以,问题是,是否所有模型和迁移都是适当生成的。如何通过在Article表中添加Category ArticleCategories来在rails控制台中对其进行测试。

从新版本开始,我已经测试了添加一个新的类别,该类别有用并添加了一个文章类别,这也有效,但我不知道在创建文章时如何添加关联。

我用过

Article.errors.full_messages

这清楚地告诉我,我需要在保存文章之前添加类别,但同样,我不知道该怎么做。

提前致谢!

2 个答案:

答案 0 :(得分:3)

您可以使用.build

@article = Article.new(:title => "foo")
@category = @article.categories.build(:name => "bar")
@article.save
#@article & @category should now have been created

或者单独制作并随后加入。

@article = Article.create(:title => "foo")
@category = Category.create(:name => "bar")
@article.categories << @category

答案 1 :(得分:-1)

@article = Article.create(:title => "foo")
@article = Article.create(:title => "foo") @article.categories << @category