-1

在我们的 rails 3.1.4 应用程序的 sys_log 模型中定义了一个质量分配:

attr_accessible :log_date, :user_name, :user_id, :user_ip, :action_logged, :as => :new_log

在 application_controller 中定义了一个方法来保存日志:

  def sys_logger(action_logged)
    log = SysLog.new(:log_date => Time.now, :user_id => session[:user_id], :user_name => session[:user_name], :user_ip => session[:user_ip],
                     :action_logged => action_logged, :as => :new_log)
    log.save
  end

但是,批量分配不起作用。这是警告消息:

WARNING: Can't mass-assign protected attributes: log_date, user_id, user_name, 
user_ip, action_logged, as

:new_log 未按定义工作。上面的代码有什么问题?非常感谢。

4

1 回答 1

1

现在:as => :new_log是属性哈希的一部分,而不是您传入的单独选项。

添加一些花括号应该会有所帮助:

def sys_logger(action_logged)
  log = SysLog.new({:log_date => Time.now, :user_id => session[:user_id],
                    :user_name => session[:user_name], :user_ip => session[:user_ip], 
                    :action_logged => action_logged }, :as => :new_log)
  log.save
end

或临时分配它:

def sys_logger(action_logged)
  attrs = { :log_date => Time.now, :user_id => session[:user_id],
            :user_name => session[:user_name], :user_ip => session[:user_ip],
            :action_logged => action_logged }
  log = SysLog.new(attrs, :as => :new_log)
  log.save
end
于 2012-05-30T06:05:37.097 回答