[英]Create model in rails console with association?
I currently have 2 models setup:我目前有 2 个模型设置:
class Topic < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :topics
end
I am now trying to create a topic with a category associated in the rails console:我现在正在尝试创建一个与 rails 控制台中关联的类别的主题:
t = Topic.new :name => "Test", :category => Category.find(1)
Trouble is the model has category_id, and so I'd need to use:问题是模型有 category_id,所以我需要使用:
c = Category.find(1)
t = Topic.new :name => "Test", :category_id => c.id
But, I've seen many times the ability to simply use :category instead of :category_id and pass in the category object instead of the objects id.但是,我已经多次看到简单地使用 :category 而不是 :category_id 并传入类别对象而不是对象 id 的能力。 Where am I going wrong?
我哪里错了?
When I do:当我做:
c = Category.find(1)
t = Topic.new :name => "Test", :category => c
I receive:我收到:
ActiveRecord::UnknownAttributeError: unknown attribute: category
You should be able to just do this:你应该能够做到这一点:
c = Category.find(1)
t = Topic.new :name => "Test", :category => c
The association definition on the model is what lets you do this.模型上的关联定义使您可以执行此操作。
Interesting note, you can use :category_id and still just pass in the object, it will get the ID for you:有趣的是,您可以使用 :category_id 并且仍然只是传入对象,它会为您获取 ID:
t = Topic.new :name => "Test", :category_id => c
Another way do do it which can be a bit nicer:另一种方法可以更好地做到这一点:
t = c.topics.build(:name => "Test") # Builds an object without saving
t = c.topics.create(:name => "Test") # Builds an object and saves it
Here's an MRE of what worked for me这是对我有用的 MRE
u = User.first
Trainer.create(name: "John", user: u)
Note that there's no 'user' column in the Trainer model, only user_id, yet when we .create
the record in Trainer, we still use user
(rails knows to place the id for that user in user_id
)请注意,Trainer 模型中没有“用户”列,只有 user_id,但是当我们在
.create
中创建记录时,我们仍然使用user
(rails 知道将该用户的 id 放在user_id
中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.