Ruby on rails more elegant way to authenticate that users can edit only their own content

后端 未结 3 842
傲寒
傲寒 2021-01-07 04:07

I currently authenticate that users can edit their own content only by:

@posts = current_user.posts.find(params[:id])

Is t

3条回答
  •  耶瑟儿~
    2021-01-07 04:31

    I worked with a framework at some point that let you put mandatory conditions in find queries, but I don't think this is (natively) possible with Rails. Possibly with a plugin.

    However, sometimes you will want to query beyond the context of a single user, so you'd need a way to override that, possibly with the :except parameter of the before_filter. But then you'd have to remember current_user on the things in the excepted methods that do need to be user-specific, and forgetting to specify it could be very dangerous.

    You could save a little typing for the vast majority of cases by overriding the model's Find functionality somehow, but you're also going to make the exceptions extremely ugly and potentially dangerous.

提交回复
热议问题