2014-07-09 86 views
0

我想升級我的項目到Rails 4的has_many ..:爲了=>已經改變,所以我輕鬆地改寫了簡單的語句,如:在Rails4中重寫模型順序範圍,正確的語法是什麼?

has_many :trackbacks, :dependent => :destroy, :order => "created_at ASC" 

has_many :trackbacks, -> { order 'created_at desc' }, :dependent => :destroy 
然而

,我卡住試圖改寫:

has_many :comments, :dependent => :destroy, :order => "created_at ASC" do 
    # Get only ham or presumed_ham comments 
    def ham 
    where(:state => ["presumed_ham", "ham"]) 
    end 
    # Get only spam or presumed_spam comments 
    def spam 
    where(:state => ["presumed_spam", "spam"]) 
    end 
end 

我想:

has_many :comments -> { order 'position desc' do 
# Get only ham or presumed_ham comments 
def ham 
    where(:state => ["presumed_ham", "ham"]) 
end 
# Get only spam or presumed_spam comments 
def spam 
    where(:state => ["presumed_spam", "spam"]) 
end 
end 
}, :dependent => :destroy 

,但它不工作..有一個語法錯誤,有什麼能正確的語法

app/models/article.rb:53: syntax error, unexpected ->, expecting keyword_end 
    app/models/article.rb:63: syntax error, unexpected ',', expecting keyword_end 
    app/models/article.rb:96: syntax error, unexpected keyword_do_block, expecting => 
    app/models/article.rb:97: syntax error, unexpected tSYMBEG, expecting keyword_end 
    app/models/article.rb:97: syntax error, unexpected ',', expecting keyword_end 
    app/models/article.rb:98: syntax error, unexpected '\n', expecting => 
    app/models/article.rb:99: syntax error, unexpected '\n', expecting => 
    app/models/article.rb:103: syntax error, unexpected '}', expecting => 
    app/models/article.rb:107: syntax error, unexpected ',', expecting => 
    app/models/article.rb:109: syntax error, unexpected '}', expecting => 
    app/models/article.rb:110: syntax error, unexpected '}', expecting => 
    app/models/article.rb:111: syntax error, unexpected '}', expecting => 
    app/models/article.rb:291: syntax error, unexpected ')', expecting => 
    app/models/article.rb:295: syntax error, unexpected ')', expecting => 
    app/models/article.rb:531: syntax error, unexpected end-of-input, expecting keyword_end 
    app/controllers/application_controller.rb:42:in `get_latest_published_articles' 
    config/initializers/quiet_assets.rb:6:in `call_with_quiet_assets' 

回答

1

你能嘗試:

has_many :comments, :dependent => :destroy, -> {where(:state => ["presumed_ham", "ham"]).order("created_at ASC")}