无法向模型写入参数。 Ruby on Rails

时间:2013-09-26 09:41:55

标签: ruby-on-rails ruby

我尝试将params写入公司模型。但我有NilClass的错误未定义方法`model_name':此时的类= simple_form_for @company,url:update_settings_company_path do | f |。我必须在哪里设置@company?

控制器

def change_settings    
    @vacation_days = current_company.vacation_days
    @illnes_days = current_company.illnes_days
  end

  def update_settings
    if @company.update(company_params)
      redirect_to account_company_path, notice: t('company.settings_changed')
    else
      render action: 'change_settings'
    end
  end

private
  def company_params
    params.require(:company).permit(:vacation_days, :illnes_days)
  end

查看

.company_settings
  = simple_form_for @company, url: update_settings_company_path do |f|
    = f.error_notification
    = f.input :vacation_days
    = f.input :illnes_days
    %br
    = f.submit t('common.save'), class: 'btn'
    = link_to t('common.back'), account_company_path, class: 'btn'

路线

resource :company, only: :all do    
    get :change_settings
    post :update_settings
    patch :update_settings
  end

怎么了?请帮帮我

2 个答案:

答案 0 :(得分:0)

您未在两个操作中设置@company实例变量。您可以使用before_filter执行此操作,如下所示:

before_filter :find_company

def change_settings    
  @vacation_days = current_company.vacation_days
  @illnes_days = current_company.illnes_days
end

def update_settings
  if @company.update(company_params)
    redirect_to account_company_path, notice: t('company.settings_changed')
  else
    render action: 'change_settings'
  end
end

private

  def company_params
    params.require(:company).permit(:vacation_days, :illnes_days)
  end

  def find_company
    @company = current_company
  end

答案 1 :(得分:0)

请尝试此操作,您需要在使用之前设置实例变量。默认情况下,实例变量设置为nil。

  def update_settings
    @company = current_company
    if @company.update(company_params)
      redirect_to account_company_path, notice: t('company.settings_changed')
    else
      render action: 'change_settings'
    end
  end