2016-07-20 25 views
0

我有兩個類,AB。 B屬於A而A有許多Bs。從一個具有很多關係的類中調用類方法

我想在A中調用一個影響多個屬性的B的實例,但不一定是屬於它的所有B實例。

我試圖把方法B和調用它是這樣的:

class A 

    has_many :bs 

    def method_to_update_many(array_of_the_many_attributes) 
     array_of_the_many_attributes.each{ |n| self.bs.find_by(attribute:n).method_to_edit(update) 
    end 
end 


class B 

    belongs_to :a 

    def method_to_edit(update) 

    update_attribute(:attribute, update) 

    end 

    end 

,並通過把的方法,在這樣的:

class A 
    has_many :bs 
    def update_a_b(b_identifier, update) 
     the_b = self.bs.find_by(identifier: b_identifier) 
     the_b.update_attribute(:attribute, update) 
    end 
end 

class b 
    belongs_to :a 
end 

似乎一切我嘗試失敗,因爲B通過CollectionProxy在與A相關時被調用。

+0

使用簡單'B.find_by'。 –

+0

我不完全確定我理解你的問題,但'#find_by'只會返回一條記錄。你可能想使用'#where' – sixty4bit

回答

0

沒有完全理解,但我認爲,您需要使用#where#update_all而不是#find_by#update_attribute。喜歡的東西

self.bs.where(identifier: b_identifier).update_all(attribute: update) 
相關問題