Calling model custom method in controller

时间:2015-07-29 00:45:50

标签: ruby-on-rails ruby methods controller

I'm trying to call a custom method I created in my model, in my controller but when I submit my form that points to the controller action, I get the following error:

undefined method `add_manager' for #Rally:0x4c1fa90

config :my_app, MyApp.Endpoint,
  render_errors: [default_format: "json"]

Here is what I have in my code

rally.rb

def add_manager
    if @rally.add_manager(manager_params)
      format.html { redirect_to @rally, notice: 'Manager successfully added.' }
      format.json { head :no_content }
    else

rallies_controller.rb

def self.add_manager(params)
    user = User.where(:email => params[:email])
    rally.users << user
end

Testing I've done so far:

  • Check the @rally is set: works
  • Checked listed methods available: add_manager was not listed
  • Tested all commands in rails console: works

Any idea what I'm doing wrong?

1 个答案:

答案 0 :(得分:0)

更改课程方法:

def self.add_manager(params)

到实例方法:

def add_manager(params)

因为@rally是你的Rally类的实例

(在上面的评论中回答 - 从未答复的列表中删除)