How do I convert a simple ruby flashcard program into a ROR app?
What I'm trying to do is make a basic flashcard app on rails. At this point, all I'm looking for is the functionality to iterate through a list of flashcards, quiz the user and let the user know if they were right or not. In ruby, it didn't take me long to write:
class Card
attr_accessor :answer, :question
def initialize(answer = "", question="")
@answer = answer
@question = question
end
def quiz
puts "What does #@question mean?"
answer = gets.chomp
if answer == @answer
puts "Right"
return true
else
puts "Wrong"
return answer
end
end
end
class Cardlist
attr_accessor :Cards
def initialize(Cards = [])
@Cards = Cards
end
def quiz
开发者_高级运维Cards.each do |w|
w.quiz
end
end
end
The problem I'm having with rails is figuring out where to put the logic to loop through all the cards in the list. I've made these two models:
class Card < ActiveRecord::Base
belongs_to :cardlist
end
and
class Cardlist < ActiveRecord::Base
has_many :cards
end
I know application logic should go in the controller, but if I were to make a "quiz" action for my Cardlist controller, how would I make it iterate through all the cards? After each "quiz" page generated, I'd need to get an answer back from the user, respond (maybe flash) whether it was right or not and then continue onto the next question. Would any of that logic have to go into the view in order to make sure it's sending back the user inputted answers to the controller? How do I send back information to the controller without writing it to the DB?
IMO, a CardList
instance is initialized and stored in the session when the user starts the quiz (you could also give the user the option to restart, which would be another method on the existing/another controller). So the CardList would be sitting in the session on the user and you would, on each quiz, give 'em another Card
.
So your "each" method would divided up between web hits, if you will.
So your view displays the Card
to the user, who answers and hits the method on the controller, where they get moved to the next Card
and shown the view again. Using the flash
variable is a fine way to give feedback to the user about the preceding commit.
As you've done, your card would typically be an ActiveRecord model. You made your CardList an ActiveRecord model too, which is a fine way to go.
Please note that you might want to use some different terms for quiz
and quiz
(like QuizSet?) to keep things a bit clearer.
精彩评论