【问题标题】:Can I use the syntax parent.Childs.create multiple times, when declaring a parent and two child records?在声明父记录和两个子记录时,我可以多次使用语法 parent.Childs.create 吗?
【发布时间】:2013-05-02 19:04:32
【问题描述】:
customer=Customer.new #create a new Customer object
customer.id =1000+i #Id needs to be set first because otherwise its automatically set
customer.update_attributes(
    :fname=>'mike',
    :lname=>'hancock',
    :Year=>1998,
    :Model=>'buick',
    :Engine=>'4 liter',
    :vinnum=>'h920129801298',
    :signupdate=>"#{Date.today}",
    :password=>'fguygfyed',
)
    contact=Contact.create(
        :customer_id=>customer.id, #set the foreign primary key
        :contactmethod=>4567894561,
        :contacttype=>"sms",
        :dateadded=>"#{Date.today}",
    )
    customer.Contacts.create(
        :contactmethod=> 4657894564,
        :contacttype=> 'email',
        :dateadded=> "#{Date.today}",
    )
    i+=1
end

此代码有效。但是,如果不是

contact=Contact.create( :customer_id=>customer.id, #设置外键

我只是像我最后写的那样写了 customer.Contacts.create 然后代码失败了。为什么我只能有一个 customer.Contacts.create 实例,而另一个我必须明确声明 customer.id?

【问题讨论】:

    标签: ruby-on-rails ruby database activerecord


    【解决方案1】:

    方法名称几乎总是全部小写。这似乎无效。

    你可能想要的是:

    customer.contacts.create(...)
    

    【讨论】:

    • 我给你的代码有效,但我会测试你的代码,看看它是否有效。也许您想查看我的代码的其他部分以了解我的问题?
    • 对不起,tadman,刚刚测试了你的代码,它产生了一个错误。
    • 您的大写和小写列的组合非常不规则,因此如果您声明了has_many :Contacts,它可能会按您的意愿工作。但是,这是非常不标准的,应该避免,小写名称是惯例。
    • 如果失败,您将需要更具体。它会产生什么错误?例外?
    • rake aborted!undefined method `contacts' for #<0x4be0820>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 2018-04-23
    相关资源
    最近更新 更多