【问题标题】:How to create a related object via Rails command line / getting error for .build如何通过 Rails 命令行创建相关对象/获取 .build 错误
【发布时间】:2015-01-22 19:45:55
【问题描述】:

我有一个用户,他有一个 has_one 可以这样配置:

class User < ActiveRecord::Base
  has_one :profile
...
class Profile < ActiveRecord::Base
  belongs_to :user

我认为我可以build 个人资料,但我收到以下错误:

@user37=User.find(37)
[9] pry(main)> @user37.profile.build
  Profile Load (0.3ms)  SELECT `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` = 37 LIMIT 1
NoMethodError: undefined method `build' for nil:NilClass
from (pry):9:in `__pry__'
[10] pry(main)> 

如何通过 Rails cli 建立这种关系?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2


    【解决方案1】:

    has_one 关系与 has_many 有点不同。因此,您需要改用@user37.build_profile

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2021-09-18
    • 1970-01-01
    相关资源
    最近更新 更多