0

I already found a workaround for my problem, but I still don't get why this problem occurs. I think i am missing some things about how internals working.

I am calling *check_modify_rights* method from couple of controllers, and I want to have a variable with appropriate name (@post for post_controller instead of a generic one, like @object)

So after before_filter runs, I expect to have a @post instance variable with a Post model. But I get a new Post model (because of @post = Post.new), and when I checked object_id s in the method, they are different.

# post_controller
  before_filter do |f|
    @post = Post.new
    f.check_modify_rights @post
  end

# application_controller
  def check_modify_rights(obj)
    return redirect_to login_path, :notice => "Please login" unless @user

    p obj.object_id
    obj = obj.class.find(params[:id])
    p obj.object_id

    return if obj.user.id == @user.id or @user.is_admin?

    redirect_to posts_path, :notice => "You don't have permission for this action"
  end
end
11
  • 1
    Obviously @post = Post.new will have a different id from a newly instantiated object Commented Dec 30, 2012 at 18:00
  • Yeah I can see that, but I am only changing obj 's value, and since @answer variable is a pointer to actual value, I expected to change its value. Am I wrong? Commented Dec 30, 2012 at 18:03
  • 1
    Nope, you instantiate a new object when you do obj = obj.class.find(params[:id]) Commented Dec 30, 2012 at 18:04
  • Damn! you are right of course. I thought obj just like pointer and expected it points the same memory region as @answer, thus I thought @answers's value also should be changed when value changed that obj points. Commented Dec 30, 2012 at 18:09
  • 1
    ok, added a better solution in bonus :) Commented Dec 30, 2012 at 18:25

1 Answer 1

1

Obviously @post = Post.new will have a different id from a newly instantiated object.

To retrieve the new object you could:

1) use a generic instance variable: @resource = Post.new

2) or:

# in your before filter
@post = f.check_modify_rights @post
# in application controller
return obj if obj.user.id == @user.id or @user.is_admin?

But basically, you're redoing Cancan, which I'd not recommend.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! I didn't notice return **obj** if obj.user.id == @user.id or @user.is_admin?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.