开发者

In Rails 3 app, how do I allow anonymous users to access a controller action only once?

开发者 https://www.devze.com 2023-04-11 03:33 出处:网络
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\"

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):

  1. Define which information should be stored in a session and / or a cookie. I think it should be the id of the comment for each flagged comment. Store them in a hash like structure.
  2. 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]
    
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号