NL-Kevin
NL-Kevin

Reputation: 197

Ruby Syntax - Position of an Array

Could you help me understand why the following code works:

def activity_params
  params.require(:activity).permit(:name, :description, :location, :user_id, category_ids: [])
end

Yet when I put the array somewhere in the middle instead of last, I get a syntax error:

def activity_params
  params.require(:activity).permit(:name, :description, :location, category_ids: [], :user_id)
end

Upvotes: 2

Views: 72

Answers (2)

simonwo
simonwo

Reputation: 3391

Keyword arguments (named arguments that end in a colon) must come after all positional arguments, as described in the Arguments documentation:

When mixing keyword arguments and positional arguments, all positional arguments must appear before any keyword arguments.

Your category_ids is a keyword argument and the others are symbols treated as positional arguments, which is why they all have to be first.

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187004

Ruby lets you skip a lot of punctuation that other languages require. In this case, Ruby is making some assumptions about your syntax that may not be obvious. Here's how it's being parsed:

permit(:name, :description, :location, :user_id, { :category_ids => [] })

permit is receiving 5 arguments: 4 symbols, and one hash. In arguments to methods, the last parameter can be a hash but without the hash literal notation of {}.

When you move that hash syntax to the middle of the argument list, it's no longer last, and therefore considered a syntax error.

Knowing this, I believe that if you make it an explicit hash, then it should work here:

permit(:name, :description, :location, { category_ids: [] }, :user_id)

Upvotes: 3

Related Questions