Nobita
Nobita

Reputation: 23713

Routes regex constraint not working as expected with subgroup in Rails 4

I have the following constraint:

get '/:name' => "products#show", :as => :product, :constraints => {name: /\w+(-\w+)*/}

The following URL:

/aa--aa

Will return a No route matches [GET] "/aa--aa"

But if I do /\w+(-\w+)*/.match('aa--aa') I will get a MatchData object. So, how does Rails handles Regex constraints? Why is this not being consistent with .match?

Upvotes: 0

Views: 107

Answers (2)

Nobita
Nobita

Reputation: 23713

Rails will embed your constraint as this:

/\A#{tests[key]}\Z/ === parts[key]

See this: formatter

That's why this won't pass.

Upvotes: 1

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51380

The ^\w+(-\w+)*$ regex cannot match aa--aa, because dashes need to be separated by words.

I don't know Ruby but I suppose ^ and $ are implicit in your constraints, and I guess you're getting a result for the aa substring because the anchors are no longer implied (I may be totally wrong here).

I suggest the following pattern:

\w+(?:-+\w+)*

I just added a + quantifier to the dash, and made the group non-capturing.

Upvotes: 0

Related Questions