ruby on rails - How to update a resource as current user or a non-user? -



ruby on rails - How to update a resource as current user or a non-user? -

in application have next resources post , user. want user able update own post , invitee post , want invitee able update other invitee post not users. invitee non-user (@post.user.blank).

post model belongs_to :user # columns: user_id, name, body end user model has_many :posts end

my controller confused because i'm not sure how create updating post can done current user or invitee without allowing update anyones post. user updating users post.

def update @post = post.find(params[:id]) if @post.update(post_params) redirect_to @post else render action: 'edit' end end def post_params params.require(:post).permit(:name, :body) end

i thinking of doing:

def update @post = post.find(params[:id]) if @post.user == current_user or @post.user.blank? if @post.update(post_params) redirect_to @post else render action: 'edit' end end end

but i'm not sure how safe is. seems user can users post.

is right? how this?

my approach utilize custom validation 'update_user' additional attribute on memory follows:

class post < activerecord::base belongs_to :user attr_accessor :update_user validate :validate_user_scope, on: :update private def validate_user_scope if !(user.blank? || user == update_user) errors.add(:update_user, :not_permitted) end end end class user < activerecord::base has_many :posts end

this merit is, of course, check logic done under rails validation @ model level (not controller).

user's access scope (or access permission) should 1 of "business logic" , "business logic" should 1 of model logic write in model level, think.

i think user2784630's check logic @ next fragment should ok:

if @post.user == current_user or @post.user.blank?

but, if worry comprehensiveness of logic, let's write test or rspec. next illustration of test/models/post_test.rb fixtures:

require 'test_helper' class posttest < activesupport::testcase ... # test of posts of guest, user-a, , user-b updated # guest, user-a, , user-b test "update invitee post user_a" p = posts(:guest_post) p.update_user = users(:user_a) assert p.valid? end ... end

ruby-on-rails ruby ruby-on-rails-4

Comments

Popular posts from this blog

java Multi query from Mysql using netbeans -

c# - DotNetZip fails with "stream does not support seek operations" -

c++ - StartServiceCtrlDispatcher don't can access 1063 error -