Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

unknown attribute error after including load_and_authorize_resource in Rails 4 #886

Closed
chrisvfritz opened this Issue Jun 21, 2013 · 1 comment

Comments

Projects
None yet
1 participant

I'm working in Rails 4 and have gotten CanCan to work well with instructions from this issue, except for one use case that I think might be relatively common.

I have a Comment model, which has_many :comments, through: :replies for nested comments. All of this is working well, until I add load_and_authorize_resource to my comments controller. The problem seems to stem from a hidden field sending an optional :parent_comment_id attribute to my create action.

I've permitted this attribute via strong parameters:

def comment_params
  params.require(:comment).permit(:content, :parent_comment_id, :post_id, :comment_id, :user_id)
end

So that I can create the association if a :parent_comment_id is included:

if comment_params[:parent_comment_id] != nil
  Reply.create({:parent_comment_id => comment_params[:parent_comment_id], :comment_id => @comment.id})
end

But once I add load_and_authorize_resource, I get an unknown attribute error for :parent_comment_id. What am I missing?

Solution came to me in my sleep. Here's what I did to solve the problem:

The only reason comment_params wasn't normally having a problem on create, was because I was excluding the extra :parent_comment_id parameter, like this:

@comment = post.comment.create(comment_params.except(:parent_comment_id))

When CanCan used the comment_params method however, it did no such sanitation. Hence, the problem. It would have been messy to add that sanitation to CanCan on a per-controller basis, so I did what I should have done all along and instead of passing the :parent_comment_id inside :comment, I used hidden_field_tag to pass it outside of :comment and accessed it through plain, old params.

I hope this helps someone else who makes a similar mistake!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment