2015-09-04 31 views
0
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"=>"[email protected]"}}}) 
    (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', '[email protected]', 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"> 

问:如何添加一个条目到模型的has_many:通过

  1. 为什么添加2记录?
  2. 要在帐户模型中添加单个项目,并填写field_id,project_id,email?
+0

你的问题在不清楚? –

回答

0

第一个帐户记录被自动创建,因为Site通过Account相关Project

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

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

+0

喜欢使用散列 {“url”=>“site.ru”,“accounts_attributes”=> {“0”=> {“email”=>“[email protected]”}}} Add INSERT INTO'sites'('url')VALUES('site.ru') INSERT INTO'accounts'('project_id','site_id','email')VALUES(1,3,'[email protected]') – user1415485

相关问题