2015-09-04 58 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

相關問題