加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails – 添加不在模型和更新模型属性中的属性

发布时间:2020-12-17 04:22:20 所属栏目:百科 来源:网络整理
导读:我的表单中有3个字段,不在我的数据库中:opening_type,opening_hours,opening_minutes.我想用这3个字段更新主要属性“打开”(在数据库中). 我尝试了很多不起作用的东西. 其实我有: attr_accessor :opening_type,:opening_hours,:opening_minutes def openin
我的表单中有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_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,你的代码就会变得更干净.

你的另一个问题是你的opens =方法永远不会被调用,这是有道理的,因为你的代码中没有任何地方可以调用它.您真正想要的是在设置完所有单独部件后设置开口.现在没有什么简单的方法可以做到这一点,但是Rails确实有一个before_validation回调,你可以放置在设置值之后但在验证运行之前运行的代码:

class Shop < ActiveRecord::Base

  attr_accessor :opening_type,: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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读