In Rails 3 app, how do I allow anonymous users to access a controller action only once?
For example, suppose I had a blog and anybody could read the articles, read the comments, and flag any comment as inappropriate. How do I prevent non-signed-in users from clicking the "Flag Comment" link more than once?
The "Flag Comment" link would be tied directly to a controller method for a Comment model.
I'm new to the idea of sessions and cookies (as well as Rails in general). I've read this on Sessions 开发者_C百科but I'm afraid I'm still a little confused.
I've considered creating a Base class called Guest, but I was wondering if I could avoid this and instead utilize session or cookies temp data.
Thanks in advance.
The basic idea could be the following (sorry, no code yet):
- Define which information should be stored in a session and / or a cookie. I think it should be the
id
of thecomment
for each flagged comment. Store them in a hash like structure. Make the link to
flagging a comment
depending on the content of the cookie. Something like that:... = link_to('flag comment', flag_comment_path(comment.id)) if ! cookies[:flagged_comments] || ! cookies[:flagged_comments][comment.id]
Set the cookies hash value when a comment is flagged (use here the local variable
comment
, this has to be set or known somewhere):cookies[:flagged_comments] = Hash.new if ! cookies[:flagged_comments] cookies[:flagged_comments][comment.id] = comment.id
I don't know if the code will work, but the idea should be clear. And yes, do that only to anonymous users (more dependent UI and controller functionality).
One more thing: I don't think you should use the session and the cookies for storing this information. And due to the fact that you have to notice when someone flags a comment in 2 different sessions, go with the cookies only.
精彩评论