항목이 7 일 이상 경과했는지 여부를 확인하기 위해 (지금은) 페이지가로드 될 때마다 필터를 실행하기 전에이 기능을 사용하고 싶습니다. 그것의 속성을 업데이트합니다.레일 - before_filter를 사용하여 메소드 실행
응용 프로그램 컨트롤러에 before_filter :update_it
이 있습니다.
def update_it
@books = Book.all
@books.each do |book|
book.update_queue
end
end
그런 다음
update_queue
이 책 모델에 정의되어
update_it
는 같은 컨트롤러에 그 아래에 정의되어 있습니다. 다음은이 관련된 모델의 모든입니다 :
scope :my_books, lambda {|user_id|
{:conditions => {:user_id => user_id}}
}
scope :reading_books, lambda {
{:conditions => {:reading => 1}}
}
scope :latest_first, lambda {
{:order => "created_at DESC"}
}
def move_from_queue_to_reading
self.update_attributes(:queued => false, :reading => 1);
end
def move_from_reading_to_list
self.update_attributes(:reading => 0);
end
def update_queue
days_gone = (Date.today - Date.parse(Book.where(:reading => 1).last.created_at.to_s)).to_i
# If been 7 days since last 'currently reading' book created
if days_gone >= 7
# If there's a queued book, move it to 'currently reading'
if Book.my_books(user_id).where(:queued => true)
new_book = Book.my_books(user_id).latest_first.where(:queued => true).last
new_book.move_from_queue_to_reading
currently_reading = Book.my_books(user_id).reading_books.last
currently_reading.move_from_reading_to_list
# Otherwise, create a new one
else
Book.my_books(user_id).create(:title => "Sample book", :reading => 1)
end
end
end
나의 관계는 그 사용자와 사용자 has_many 책 belongs_to 책. 나는 사용자 쇼보기를 통해보기에 이러한 책을 보여 주지만 중요하지는 않습니다.
그래서 계속 오류가 발생하는 것은 move_from_queue_to_reading
및 move_from_reading_to_list
은 정의되지 않은 방법입니다. 어떻게 이럴 수있어? 나는 그것들을 명확하게 정의하고있다. 나는 정말 실망스럽고 내가 잘못하고있는 것에 대한 통찰력을 크게 고맙게 생각할 것입니다. 여기 초보자를, 그래서 어떤 구조적인 비판은 좋은 것입니다 :)
편집
정확한 오류 메시지 내가 얻을 다음과 같이 스택 추적은 다음과 같습니다
NoMethodError in UsersController#show
undefined method `move_from_queue_to_reading' for nil:NilClass
app/models/book.rb:41:in `update_queue'
app/controllers/application_controller.rb:22:in `block in update_it'
app/controllers/application_controller.rb:21:in `each'
app/controllers/application_controller.rb:21:in `update_it'
당신은'new_book'와'currently_reading' 변수는'nil' 아니라는 것을 확인 할 수 있나요? – PinnyM
'protected' 또는'private' 섹션에서 찾을 수없는 두 가지 방법이 있습니까? –
@PinnyM'''new_book'''은 콘솔에서''''new_book = Book.where (: queued => true) .last'''를 실행하면 nill이 아닙니다. 책을 반환합니다. '''currently_reading'''과 같은 것. –