Rails – 添加不在模型和更新模型属性中的属性

我的表单中有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 

我尝试添加类似的东西:

  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_readerattr_writerattr_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回调,你可以放置在设置值之后但在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 

代替

 attr_reader :opening_type, :opening_hours, :opening_minutes 

你需要

 attr_accessor :opening_type, :opening_hours, :opening_minutes attr_reader :opening_type, :opening_hours, :opening_minutes 

HF …

//是:opening_type,:opening_hours,:opening_minutes真实字段? 如果是,那么你只需要这个吗?

attr_accessor:打开attr_reader:打开