簡體   English   中英

Rails - 添加不在模型和更新模型屬性中的屬性

[英]Rails - Add attributes not in model and update model attribute

我的表格中有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回調,你可以放置在設置值之后但在驗證運行之前運行的代碼:

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:打開

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM