ruby PORO表单对象和父对象未初始化

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby PORO表单对象和父对象未初始化相关的知识,希望对你有一定的参考价值。

Loading development environment (Rails 4.0.2)
[1] pry(main)> j = Job.new
=> #<Job id: nil, name: nil, client_id: nil, description: nil, job_type_id: nil, properties: {}, created_at: nil, updated_at: nil>
[2] pry(main)> c = Client.new
=> #<Client id: nil, business_name: nil, contact_name: nil, shop_no: nil, street_no: nil, street_name: nil, suburb: nil, phone: nil, updated_at: nil, created_at: nil, email: nil>
[3] pry(main)> form = JobSheet.new(j, c)
ArgumentError: wrong number of arguments (2 for 1)
from /Users/egray/Documents/www/comprint/app/forms/form_object.rb:4:in `initialize'
[4] pry(main)> 
class JobSheet < FormObject
 
  # include ActiveModel::Model
 
# Client
  attr_accessor(
    :business_name,
    :email,
    :phone,
    :contact_name,
    :shop_no,
    :street_no,
    :street_name,
    :suburb
  )
  
  # Job
  attr_accessor(
    :name,
    :description,
    :properties,
    :client_id
  )
  
  validates :business_name, presence: true
  validates :email, presence: true
  validates :contact_name, presence: true
  validates :shop_no, presence: true
  validates :street_no, presence: true
  validates :street_name, presence: true
  validates :suburb, presence: true 

  # def initialize(@job, @client)
  #   @job
  # end


  # Client ID is either selected or 0
  def new_client
    @new_client ||= params[:client_id]
  end

  def submit(params)
    create_job(params[:job])
    create_client(params[:client])
    if valid?
      
      @client.save!
      @job.save!
      true     
    else
      false
    end
  end
 

  private
  
  # Create job and client
  def create_job
    @job.name        = params[:name]
    
    @job.description = params[:description]
    @job.properties  = params[:properties]
  end  

  def create_client
    if :new_client > 0
      @client.business_name = params[:client][:business_name]
      @client.email         = params[:client][:email]
      @client.contact_name  = params[:client][:contact_name]
      @client.shop_no       = params[:client][:shop_no]
      @client.street_no     = params[:client][:street_no]
      @client.street_name   = params[:client][:street_name]
      @client.suburb        = params[:client][:suburb]
    else
      @job.client_id        = params[:job][:client_id]
    end
  end
end
class FormObject
  include ActiveModel::Model
  
  def initialize(args)
    args.each do |k, v|
      instance_variable_set("#{k}", v) unless v.nil?
    end
  end
  
end

以上是关于ruby PORO表单对象和父对象未初始化的主要内容,如果未能解决你的问题,请参考以下文章

Ruby 和 SQL 中的重复业务逻辑

ruby 装饰器与表单对象与服务对象?

Ruby on Rails,带有对象方法的表单助手

不能同时添加子对象和父对象

Ruby Watir 表单下拉未找到

JNI/NDK开发指南——调用构造方法和父类实例方法