← Back to Upcase

Best Way to Implement New Route/Action?


(Brandon Newton) #1

Hi I just finished the intro to rails series and completed the Flashcards app. After finishing the series I went about recreating the app without watching the video. I was able to do so and felt confident to add on some functionality. So I tried implementing user’s supplying answers to card fronts. Currently I’m doing this:

# app/controller/cards_controller.rb
	def check_answer
		guess = params[:card][:back]
		if @card.check_answer(guess)
			flash[:success] = "Correct!"
			redirect_to [@deck, @card]
		else
			flash[:notice] = "Incorrect!"
			redirect_to [@deck, @card]
		end
	end
# app/views/cards/show.html.erb
<% if flash.to_hash.include? "notice" %>
	<div class="answer">
		<h2>Nope! The correct answer was:</h2>
		<p><%= @card.back %></p>
		<%= link_to "Next Card >>", next_card %> 
	</div>
<% elsif flash.to_hash.include? "success" %>
	<div class="answer">
		<h2>Correct! Nice Job!</h2>
		<%= link_to "Next Card >>", next_card %>
	</div>
<% else %>
	<%= form_for "card" do |form| %>
		<div>
			<%= form.label :back, "Answer:" %>
			<%= form.text_field :back, value: nil %>
		</div>
		<%= form.submit "Submit Answer" %>
	<% end %>
<% end %>
# config/routes.rb
	resources :decks do
		resources :cards, except: [:index]
		post "/cards/:id", to: "cards#check_answer"
	end

Is this the correct way to go about this? Should I be putting the check_answer method in the controller or keep it in the model? Is the way I’m routing the post correct for nested resources? Also is the way I’m handling the form in the view acceptable? I thought that form_for "card" was a little strange since I’ve been using a lot of instance variables.

Thanks guys :smiley_cat: