Rails: rake task with arguments not working
Asked Answered
G

4

29

Here is my rake task

namespace :users do
  task :change_role, [:role] => :environment do |t, args|
    puts args.role
  end
end

I am calling it like this:

rake users:change_role["role"] but I am getting this error no matches found: users:change_role["role"]

Gambrill answered 3/7, 2014 at 15:3 Comment(4)
Where are you putting this? There's nothing wrong with what you've written, or how you're invoking it.Suasion
does your rake task file has file extension as .rake?Superiority
@Superiority - my file is named users.rakeGambrill
@meagar - it's in app/lib/tasksGambrill
D
64

You need to escape the square brackets when using them in some shells like zsh:

rake users:change_role\["role"\]
Defer answered 3/7, 2014 at 16:23 Comment(6)
No it is not. That is the error from your shell telling you there are no matches for that command found. With zsh and no escaping the output is zsh: no matches found: users:change_role[ok]. Using zsh with escaping the output is okDefer
You're correct, its rake saying it can't find the command. In any case, you need to escape the brackets with zsh.Defer
Ah, actually I think you're right. "No matches found:" is definitely not being output by rake; rake would have said "don't know how to build task...".Suasion
That escaping isn't correct... I tried this rake users:change_roles[\"hello\"] and I am still getting the same errorGambrill
Did you mean rake users:change_role[\"hello\"]?Defer
Great call! the full error is indeed: zsh: no matches found:Cannery
T
31

Put the rake task in single quotes.

rake 'users:change_role["role"]'

more on https://thoughtbot.com/blog/how-to-use-arguments-in-a-rake-task

Throne answered 16/11, 2019 at 13:18 Comment(3)
The only thing that works for me (Rails 5.0.7.2)!!Obeisance
This is a zsh prereq.Mithraism
we should ask the OP if he is using zhs or not. But this helped me, as I just switched to zhs.Vladi
W
10

You can add unsetopt nomatch to your .zshrc file, as Chad Pytel describes in here

Weave answered 29/11, 2018 at 9:44 Comment(1)
You the man, dog. This is the right answer for most people, especially those that are coming from bash.Underdrawers
A
1

@infused way works, but if you want change to be permanent, so you can simply call rake users:change_roles["hello"], add following to your .zshrc:

alias rake='noglob rake'
Asuncionasunder answered 22/3, 2015 at 8:35 Comment(1)
this is working fine with me on Ubuntu 20.4, thank youGreaves

© 2022 - 2024 — McMap. All rights reserved.