【问题标题】:ruby initialize method arguments mismatchruby 初始化方法参数不匹配
【发布时间】:2021-03-29 20:53:09
【问题描述】:

我正在 Sinatra 中使用 activerecord 编写应用程序,所以我想我的问题与 Rails 中的相同。

class Entry < ActiveRecord::Base

    require 'date'
    belongs_to :bankaccount

end


class Recurrent < Entry

    attr_accessor :date_1, :date_2, :monthly_entry

    def initialize (date_1, date_2)
        @date_1 = date_1 # format DateTime.new(2020,12,5) 
        @date_2 = date_2
    end

    # other methods

当我运行这段代码时,我得到:

>> date_1 = DateTime.new(2020,12,5)
>> date_2 = DateTime.new(2021,11,5)
>> recurrent = Recurrent.new(date_1, date_2)
**ArgumentError (wrong number of arguments (given 2, expected 0..1))**

当我删除参数时,我收到以下错误消息:

>> recurrent = Recurrent.new
**ArgumentError (wrong number of arguments (given 1, expected 2))**

当我在普通 ruby​​ 中执行此操作并在 irb 中运行它时,因此没有 activerecord,它可以正常工作。

【问题讨论】:

    标签: ruby class activerecord arguments sinatra


    【解决方案1】:

    根据the documentation

    创作

    Active Record 接受散列或块形式的构造函数参数。当您从其他地方接收数据(例如 HTTP 请求)时,哈希方法特别有用。它的工作原理是这样的:

    user = User.new(name: "David", occupation: "Code Artist")
    user.name # => "David"
    

    你也可以使用块初始化:

    user = User.new do |u|
      u.name = "David"
      u.occupation = "Code Artist"
    end
    

    当然你也可以只创建一个裸对象并在事后指定属性:

    user = User.new
    user.name = "David"
    user.occupation = "Code Artist"
    

    所以,ActiveRecord 对象允许三种不同的创建方式:

    • 无参数,稍后设置属性。
    • 块参数。
    • 一个Hash 参数。

    它们不允许两个参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      相关资源
      最近更新 更多