简体   繁体   English

数组元素的自定义访问器

[英]Custom accessor for array element

I'm trying to create an accessor for one element from array with specific flag set to true: 我正在尝试为数组中的一个元素创建一个访问器,并将特定标志设置为true:

class EntranceObject < ActiveRecord::Base
  has_many :subscribers

  def customer
      self.subscribers.find(:first, :conditions => {:is_customer => true})
  end

  def customer=(customer_params)
    self.subscribers << Subscriber.new(:name => customer_params[:name],
                                       :apartment => customer_params[:apartment],
                                       :phone_number => customer_params[:phone_number],
                                       :is_customer => true)
  end
end

class Subscriber < ActiveRecord::Base
  belongs_to :entrance_object

  validates_presence_of :name, :apartment         
end

How do i need to validate this accessor in order to hightlight missing fields in a view? 我如何验证此访问器以突出显示视图中的缺失字段?

PS I'm newbie in RoR, maybe there is another approach to such work with one element from a collection? PS我是RoR的新手,也许有另一种方法可以处理集合中的一个元素? Thanks. 谢谢。

You can have Rails magic do the work for you. 您可以让Rails magic为您完成工作。

class EntranceObject < ActiveRecord::Base
  has_many :subscribers
  has_one :customer, :class_name => "Subscriber", :foreign_key => "entrance_object_id", :conditions => {:is_customer => true}

  validates_associated :customer
end

The validates_associated will validate the customer object and store the errors in entrance_object.customer.errors (so you will have to do so some work in showing all the errors in the view). validates_associated将验证客户对象和存储中的错误entrance_object.customer.errors (所以你必须这样做了一些工作在显示视图中所有的错误)。

See here for docs on validates_associated . 请参阅此处以获取有关validates_associated文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ActiveModel的自定义属性的attr_accessor用法 - attr_accessor usage for a custom attribute of ActiveModel 使用attr_accessor缓存模型数组? - Cache Model array with attr_accessor? 如何在Ruby中使用动态参数声明自定义属性访问器? - How to declare custom attribute accessor with dynamic argument in Ruby? 带有“ class Class”和自定义attr_accessor的Rails lib /模块 - Rails lib/module with 'class Class' and custom attr_accessor Mongoid,在 mongoid-history gem 中设置自定义访问器字段 - Mongoid, setting custom accessor field in mongoid-history gem 获取自定义attr_accessor的未定义方法`validates_presence_of&#39; - Getting a undefined method `validates_presence_of' for for a custom attr_accessor 非模型数组元素的Rails attr_accessor - Rails attr_accessor for non model array elements Ruby - 使用 jsonb_accessor 更新 jsonb 数组列设置 - Ruby - Update jsonb array column setup with jsonb_accessor 使用rails4stored_accessor在Postgres中搜索jsonb和数组组合 - Search in jsonb and array combination in postgres with rails4 stored_accessor 在到达模型验证之前捕获自定义访问器中引发的异常(并在错误[]中向用户显示它) - Catching an exception raised in custom accessor before reaching model validation (and showing it to the user in errors[])
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM