2012-11-18 38 views
1

我試圖設置一個has_manyconditions它適用於閱讀部分,但不適用於新條目。我在沙盒測試它幾個星期前,它的工作,但我不能得到它的工作再次所以也許我只是盲目的或者它僅僅是一個錯誤的設計:-)Rails has_many源代碼和條件不會創建條件屬性

class Task 
    has_many :task_users 
    has_many :assignees, :through => :task_users, :source => :user, :conditions => {"task_users.is_assignee" => true} 
    has_many :participants, :through => :task_users, :source => :user 
end 

class TaskUser < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :task 
end 

class User 
    has_many :tasks 
end 

加入後新的受讓人任務這樣

Task.first.assignees << User.first 

以下SQL執行

SQL (0.3ms) INSERT INTO `task_users` (`created_at`, `is_assignee`, `task_id`, `updated_at`, `user_id`) VALUES ('2012-11-18 15:52:24', NULL, 2, '2012-11-18 15:52:24', 3) 

我想軌會用我的條件,當我加荷蘭國際集團新的設置這些值。閱讀很好,但我不知道爲什麼添加新值不符合條件。

我希望這INSERT

SQL (0.3ms) INSERT INTO `task_users` (`created_at`, `is_assignee`, `task_id`, `updated_at`, `user_id`) VALUES ('2012-11-18 15:52:24', 1, 2, '2012-11-18 15:52:24', 3) 
+0

就是所謂的連接表'task_users'或'item_users'?它看起來像你正在交替使用這些。你能澄清嗎? – cdesrosiers

+0

它被稱爲'task_users'只是misstyped'任務'有'項目'有時:( 修正了我的文章中的拼寫錯誤 – Mike

回答

1

我不完全確定您是否可以在has_many :through關聯中的連接表上指定:conditions散列。其他人糾正我,如果我錯了,但條件必須直接在源協會,:user你的情況。

如果是這種情況下,要解決這一點,你可以指定一個輔助協會:

has_many :task_users 
has_many :assignee_task_users, :class_name => 'TaskUser', :conditions => {"is_assignee" => true} 
has_many :assignees, :through => :assignee_task_users, :source => :user 
+0

哇這就是它第一次測試的工作,但需要深入一點點深入一點點今天下午 – Mike

+0

完美的解決方案! 謝謝 – Mike

0

只是要突出文檔:

Specify the conditions that the associated objects must meet in order to be 
included as a WHERE SQL fragment, such as price > 5 AND name LIKE 'B%'. 
Record creations from the association are scoped if a hash is used. 
has_many :posts, :conditions => {:published => true} will create published 
posts with @blog.posts.create or @blog.posts.build. 
即使你使用的已經是一個哈希

,第一個參數是一個字符串,它是unneded是(該關聯已知該表名)。將其重寫爲:conditions => {:is_assignee => true},它應該可以工作。

此外,您創建用戶的方式應該重寫,以便當然可以工作。相反的:

Task.first.assignees << User.first 

使用:

Task.first.assignees.create 

而且應該做的伎倆。

+0

昨天我試過':conditions => {:is_assignee => true}'''''因爲我正在使用'源' 我試過.create,但不能得到它的工作 – Mike