ale*_*our 7 ruby-on-rails accessor
我的表格中有3个字段,不在我的数据库中:opening_type,opening_hours,opening_minutes.我想用这3个字段更新主要属性"打开"(在数据库中).
我尝试了很多不起作用的东西.
其实我有:
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
Run Code Online (Sandbox Code Playgroud)
我尝试添加类似的东西:
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
Run Code Online (Sandbox Code Playgroud)
但是,访问器方法没有调用,我认为如果调用访问器,opening_type,opening_hours,opening_minutes也是空的...
我想我不需要before_save回调,应该重写访问器.
注意: - Rails 3.0.5, - opening_type,:opening_hours,:opening_minutes可能为空
编辑:我更新了我的代码
Gar*_*eth 16
需要注意的是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)
Run Code Online (Sandbox Code Playgroud)
目前,你的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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20163 次 |
| 最近记录: |