我正在Rails 3.2.17
尝试访问模型中的两个虚拟属性(expiration_amount
& expiration_format
),但我尝试过的任何方法都不允许我访问它们。
其他一切似乎都正确更新,但是在我的日志中,虚拟属性总是空白。
编辑我按照建议添加了两者:expiration_amount
:expiration_format
,attr_accessible
但它仍然无法正常工作。他们俩都是空白的。我确实注意到的一件事是记录器调用是在它到达数据库之后发生的。这before_update
不是正确的过滤器吗?
编辑 2是否有可能Devise
阻止访问虚拟属性?
编辑 3我刚决定从控制器中启动它(它正在工作),但我仍然很好奇为什么我无法访问模型中的那些虚拟属性。
工作控制器动作(更新方法)
@user.set_expiration(params[:expiration_amount].to_i, params[:expiration_format])
工作模型法
def set_expiration(amount, format)
if defined?(amount) && defined?(format)
case format
when "hours"
self.expiration = amount.hours.from_now
when "days"
self.expiration = amount.days.from_now
when "weeks"
self.expiration = amount.weeks.from_now
else
self.expiration = amount.hours.from_now
end
end
end
---原始代码---
用户.rb
class User < ActiveRecord::Base
attr_accessible :email,
:password,
:password_confirmation,
:remember_me,
:first_name,
:last_name,
:company,
:phone,
:expiration,
:expiration_amount,
:expiration_format
attr_accessor :expiration_amount,
:expiration_format
before_update :set_expiration
def set_expiration
logger.debug "DEBUG - expiration_amount: #{expiration_amount}"
logger.debug "DEBUG - expiration_format: #{expiration_format}"
if expiration_amount && expiration_format
case expiration_format
when "hours"
self.expiration = expiration_amount.hours.from_now
when "days"
self.expiration = expiration_amount.days.from_now
when "weeks"
self.expiration = expiration_amount.weeks.from_now
else
self.expiration = expiration_amount.hours.from_now
end
end
end
end
形式
= form_for(resource, :as => resource_name, :url => admins_user_update_path(resource), :html => { :method => :put }) do |f|
= devise_error_messages!
%fieldset{id: "edit-user-account"}
%legend
Set User Access
.field.required
%label
"Allow access for "
= select_tag "expiration_amount", options_for_select(expiration_amount, 3)
= select_tag "expiration_format", options_for_select(expiration_format, "days")
%span.instructions
From Now
.field
= f.submit "Grant Access"
日志
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx=", "expiration_amount"=>"3", "expiration_format"=>"days", "commit"=>"Grant Access", "id"=>"5"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", "5"]]
Admin Load (0.4ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 LIMIT 1
(0.3ms) BEGIN
DEBUG - expiration_amount:
DEBUG - expiration_format:
(0.3ms) COMMIT
Redirected to http://localhost:8080/admins/users