我的表单中有 3 个字段不在我的数据库中:opening_type、opening_hours、opening_minutes。我想用这 3 个字段更新主要属性“opening”(在数据库中)。
我尝试了很多不起作用的东西。
其实我有:
attr_accessor :opening_type, :opening_hours, :opening_minutes
def opening_type=(opening_type)
end
def opening_type
opening_type = opening.split("-")[0] if !opening.blank?
end
def opening_hours=(opening_hours)
end
def opening_hours
opening_hours = opening.split("-")[1] if !opening.blank?
end
def opening_minutes=(opening_minutes)
end
def opening_minutes
opening_minutes = opening.split("-")[2] if !opening.blank?
end
我尝试添加如下内容:
def opening=(opening)
logger.info "WRITE"
if !opening_type.blank? and !opening_hours.blank? and opening_minutes.blank?
opening = ""
opening << opening_type if !opening_type.blank?
opening << "-"
opening << opening_hours if !opening_hours.blank?
opening << "-"
opening << opening_minutes if !opening_minutes.blank?
end
write_attribute(:opening, opening)
end
def opening
read_attribute(:opening)
end
但是,访问器方法没有被调用,我认为如果访问器被调用,opening_type、opening_hours、opening_minutes 也是空的......
我想我不需要 before_save 回调,应该重写访问器。
笔记:
- rails 3.0.5,
- opening_type, :opening_hours, :opening_minutes 可以为空
编辑:我更新了我的代码
最佳答案
请注意 attr_reader
, attr_writer
和 attr_accessor
只是用于定义自己的方法的宏。
# attr_reader(:foo) is the same as:
def foo
@foo
end
# attr_writer(:foo) is the same as:
def foo=(new_value)
@foo = new_value
end
# attr_accessor(:foo) is the same as:
attr_reader(:foo)
attr_writer(:foo)
目前,你的 setter 方法没有做任何特别的事情,所以如果你只是切换到
attr_accessor
你的代码会变得更干净。您的另一个问题是您的
opening=
方法永远不会被调用,这是有道理的,因为您的代码中没有任何地方调用它。您真正想要的是在设置所有单个部分后设置您的开口。现在没有简单的方法可以做到这一点,但 Rails 确实有一个 before_validation
回调,您可以在其中放置在设置值之后但在验证运行之前运行的代码:class Shop < ActiveRecord::Base
attr_accessor :opening_type, :opening_hours, :opening_minutes
before_validation :set_opening
private
def set_opening
return unless opening_type && opening_hours && opening_minutes
self.opening = opening_type + "-" + opening_hours + "-" + opening_minutes
end
end
关于ruby-on-rails - Rails - 添加不在模型中的属性并更新模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9376744/