2012-07-03 50 views
1

我有四個型號在我的應用程序,定義爲named_scope正確的語法如下的Rails 3:與方法調用和模型關聯

class User < ActiveRecord::Base 
    has_many :comments 
    has_many :geographies 
    has_many :communities, through: :geographies 

class Comment < ActiveRecord::Base 
    belongs_to :user 

class Community < ActiveRecord::Base 
    has_many :geographies 
    has_many :users 

class Geography < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :community 

用戶可以發表評論,這是與一個或多個社區通過地理相關表。

我的任務是僅顯示從下拉列表中選擇的社區評論。我從this post得知我可以通過comment.user.communities.first對象鏈訪問給定評論的社區。

這似乎通常與拉姆達一個named_scope將過濾的所有評論列表中的首選,但是,我是在一個完全喪失瞭如何構建這個named_scope。我試圖通過遵循一些RailsCasts來構造named_scope,但是就我所能得到的而言,這已經是了。生成的錯誤如下。

class Comment < ActiveRecord::Base 
    belongs_to :user 

    def self.community_search(community_id) 
     if community_id 
      c = user.communities.first 
      where('c.id = ?', community_id) 
     else 
      scoped 
     end 
    end 

    named_scope :from_community, { |*args| { community_search(args.first) } } 

這是錯誤:

syntax error, unexpected '}', expecting tASSOC 
named_scope :from_community, lambda { |*args| { community_search(args.first) } } 
                  ^

什麼是用於傳遞方法與參數到一個named_scope正確的語法?

回答

4

首先,您現在可以在rails 3中使用scope - 較早的named_scope表單被縮短了,它在rails 3.1中的removed

關於你的錯誤,雖然,我懷疑你不需要內部的一組括號。

scope :foo, { |bar| 
    { :key => "was passed #{bar}" } 
} 

在你的情況,不過,你在呼喚community_search應返回一個值,你可以:使用像這樣的拉姆達塊時,因爲你是從頭開始創建新的哈希值,這樣它們通常一倍,直接返回。在這種情況下,一個AREL對象已經取代了這種簡單的哈希。在閱讀所有關於這個主題的隨機帖子和教程時,這有點令人困惑,這很大程度上是由於AREL引起的風格的巨大變化。儘管這兩種風格的用法都可以,不管是作爲lambda還是類方法。他們主要是指同樣的事情。以上兩個鏈接有幾個這種新的風格的例子進一步閱讀。

當然,你可能只是學到一些東西像​​,我覺得這更容易閱讀,並減少了大量的打字。 ^^;