2010-12-10 2 views
0

has_many와 연결된 두 개의 모델이 있습니다. 댓글 테이블을 만들기위한Rails3 has_many 연관이있는 범위

class User < ActiveRecord::Base 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :user 
end 

및 마이그레이션 파일은 다음과 같다 :

class CreateComments < ActiveRecord::Migration 
    def self.up 
    create_table :comments do |t| 
     t.string :body 
     t.boolean :important, :default => false 
     t.references :user 

     t.timestamps 
    end 
    end 
    ... 

한 최신으로 중요한 코멘트를 게시 사용자를 나열하려면, 나는 시도 :

scope :have_important, (joins(:comments) & Comment.order('created_at desc')).where('important = ?', true) 

를 사용자에. rb. 그러나 이것은 중요한 논평을 최신이 아닌 것으로 게시 한 사용자를 포함합니다. 어떻게 그 범위를 정의 할 수 있습니까?

단위 테스트는 여기에 있습니다 :

test "Scoped user's latest comment should be important" do 
    User.have_important.each do |user| 
    assert_equal user.comments.last.important, true 
    end 
end 
+0

나는 당신이 성취하려는 것을 완전히 모릅니다. 테스트/스펙을 작성할 수 있습니까? – iain

+0

단위 테스트가 추가되었습니다. 관련없는 주제에 – JayKay

+0

, Jamiroquai에서 프론트 맨의 이름을 따서 붙이셨습니까? 그 밴드를 사랑해 :) – Samo

답변

1

이름 "have_important은"정말 최신을 의미하지는 않습니다. 어쩌면 당신이 원하는 것은 두 가지 다른 범위, 하나는 중요하고 다른 하나는 최근입니다. 그럼 그들을 묶어 라.