I currently have a very simple model "Coupon". I suddenly am interested to add two more fields, "redeem_code" and "redeemed" to the model for obvious reasons.
开发者_运维问答I would like to make a view for a merchant to redeem a coupon based on a code.
The simplest approach that I can think of to just do this would be something like this:
def redeem
#renders the page
end
def redeem_post
redeem_code = params[:redeem_code]
deal = Deal.find_by_redeem_code(redeem_code)
if deal.nil?
# BUG: Somehow here you will be logged out
redirect_to deals_path
else
if deal.update_attribute(:redeemed, true)
redirect_to deals_path
end
end
end
As far as I am concerned, rails doesn't really support non restful interfaces. I tried digging up form helpers last night but I was not able to find anything so I just put togehter something real fast:
<form action="<%= deals_redeem_post_path %>" method="post">
<table>
<tr>
<th> Code: </th>
<td> <input type="text" name="redeem_code" /> </td>
</tr>
<tr>
<th></th>
<td> <input type="submit" text="Submit" /> </td>
</tr>
</table>
</form>
I am using devise. The bug that I am experiencing right now is when my user submits this form, he/she will be automatically logged out.
Any ideas how I can fix this or implement this more elegantly?
My guess is that you are missing the authenticity token (which prevents Cross Site Request Forgery (CSRF)) which is automatically generated. You want to use the form for helper for that generates this automatically.
<%= form_for(:coupon, :url => deals_redeem_post_path) do |f| %>
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for
精彩评论