【问题标题】:Create model in rails console with association?在带有关联的rails控制台中创建模型?
【发布时间】:2020-08-15 01:58:12
【问题描述】:

我目前有 2 个模型设置:

class Topic < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :topics
end

我现在正在尝试创建一个与 rails 控制台中关联的类别的主题:

t = Topic.new :name => "Test", :category => Category.find(1)

问题是模型有 category_id,所以我需要使用:

c = Category.find(1)
t = Topic.new :name => "Test", :category_id => c.id

但是,我已经多次看到简单地使用 :category 而不是 :category_id 并传入类别对象而不是对象 id 的能力。我哪里错了?

当我这样做时:

c = Category.find(1)
t = Topic.new :name => "Test", :category => c

我收到:

ActiveRecord::UnknownAttributeError: unknown attribute: category

【问题讨论】:

  • 你用的是什么版本的rails?
  • 我使用的是 3.1.3。谢谢。

标签: ruby-on-rails ruby


【解决方案1】:

你应该可以这样做:

c = Category.find(1)
t = Topic.new :name => "Test", :category => c

模型上的关联定义让您可以做到这一点。

有趣的是,你可以使用 :category_id 并且仍然只是传入对象,它会为你获取 ID:

t = Topic.new :name => "Test", :category_id => c

另一种更好的方法:

t = c.topics.build(:name => "Test") # Builds an object without saving

t = c.topics.create(:name => "Test") # Builds an object and saves it

【讨论】:

  • 嗨。感谢你的回答。当我按照您的第一个示例执行此操作时,我收到此错误:“ActiveRecord::UnknownAttributeError: unknown attribute: category”。我的关联是根据我的帖子设置的。也感谢您提供免费信息。
  • 如果你执行 t = c.topics.build(:name => "Test") 行,你会得到同样的结果吗?
  • 为此,我收到“NoMethodError: undefined method `topics' for #<0xaee5638>
【解决方案2】:

这是对我有用的 MRE

u = User.first

Trainer.create(name: "John", user: u)

请注意,Trainer 模型中没有“用户”列,只有 user_id,但是当我们在 Trainer 中 .create 记录时,我们仍然使用 user(rails 知道将该用户的 id 放在 user_id )

【讨论】:

    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多