如何向模型添加条目has_many:through

时间:2015-09-04 07:19:45

标签: ruby-on-rails activerecord has-many-through

class Project < ActiveRecord::Base
  has_many :accounts
  has_many :sites, through: :accounts
end

class Site < ActiveRecord::Base
  has_many :accounts
  has_many :projects, through: :accounts
  accepts_nested_attributes_for :accounts
end

class Account < ActiveRecord::Base
  belongs_to :site
  belongs_to :project
end

p = Project.find(1)

2.1.4 :011 >   p.sites.create({"url"=>"site.ru", "accounts_attributes"=>{"0"=>{"email"=>"mail@site.ru"}}})
   (0.3ms)  BEGIN
  SQL (1.8ms)  INSERT INTO `sites` (`created_at`, `updated_at`, `url`) VALUES ('2015-09-04 07:09:53', '2015-09-04 07:09:53', 'site.ru')
  SQL (0.3ms)  INSERT INTO `accounts` (`created_at`, `email`, `site_id`, `updated_at`) VALUES ('2015-09-04 07:09:53', 'mail@site.ru', 3, '2015-09-04 07:09:53')
  SQL (0.3ms)  INSERT INTO `accounts` (`created_at`, `project_id`, `site_id`, `updated_at`) VALUES ('2015-09-04 07:09:53', 1, 3, '2015-09-04 07:09:53')
   (1.2ms)  COMMIT
 => #<Site id: 3, url: "site.ru", created_at: "2015-09-04 07:09:53", updated_at: "2015-09-04 07:09:53"> 

问题:

  1. 为什么要添加2条记录?
  2. 要在帐户模型中添加一个条目,其中包含字段site_id,project_id,email?

1 个答案:

答案 0 :(得分:0)

第一个帐户记录是自动创建的,因为SiteProjectAccount相关。

创建第二条记录是因为您的accepts_nested_attributes_for :accounts模型中有Site,并且您在创建Site记录时传递了嵌套属性。

你能澄清一下,你想要什么?