开发者

Association Problem

I am having a problem with an association:

Battalion :has_many soldiers

Soldiers :has_many primaries

I need to do this @bseniorleads=(@user.battalion.soldiers.find(:all, :conditions => ["seniorleader = ?", "Yes"])) then @seniorspouse=(@bseniorleads.primaries.find(:all, :conditions => ["relationship = ?", "Spouse"]

This gives me an undefined method for primaries, I assume because the bsenior开发者_Go百科leads is an array?

Basically I don't know how to do this they right way but I need to be able to query a group from one model that meets a condition and then take that result and find the people from another model that belong to them. Any ideas?

Thanks in advance.


You should be able to do something like this (assuming you only needed the @bseniorleads instance variable in the second query):

@senior_spouse = @user.battalion.soldiers.find(
   :all,
   :select => 'primaries.*',
   :joins => [:primaries],
   :conditions => ["seniorleader = ? and primaries.relationship = ?", "Yes", "Spouse"]
)

I haven't checked that yet, but I think it should get you pretty close.

You might want to check out these two rails guides, which certainly helped me better understand ActiveRecord associations and querying:

  • ActiveRecord Querying
  • ActiveRecord Associations
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜