简体   繁体   English

为什么链接模型查询/分配在Rails控制台中不起作用?

[英]Why doesn't chaining Model queries / assignments work in rails console?

How come this works in the rails console: 在rails控制台中这是如何工作的:

foo = Ad.find(2)
foo.user = User.find(1)
foo.user # => #<User id: 1, name: "john">

But this doesn't? 但这不是吗?

Ad.find(2).user = User.find(1)
Ad.find(2).user  # => nil

Because each time you write Ad.find(2) it is returning a new instance of the Ad class whose ID is 2, and your code is changing the associated User on that instance but never saving the change . 因为每次编写Ad.find(2)它都会返回ID为2的Ad类的新实例,并且您的代码正在更改该实例上的关联User,但从不保存更改 So in this line: 所以在这一行:

Ad.find(2).user = User.find(1)

you fetch an instance of Ad with ID 2, set that instance's user association to User.find(1) , but this change is never saved to the database, and is lost once the statement ends. 您获取ID为2的Ad实例,则将该实例的user关联设置为User.find(1) ,但此更改永远不会保存到数据库,并且在语句结束时丢失。 In the next line: 在下一行:

Ad.find(2).user  # => nil

you are just fetching another instance of Ad with ID 2, but since the previous change was never persisted to the DB, user is nil . 您只是在获取ID为2的Ad的另一个实例,但是由于之前的更改从未保存到数据库中,因此usernil

Like you showed in the first code snippet, you must use a local variable to temporarily keep a reference to your Ad instance in order to call .save on it, in order to persist to the DB. 就像您在第一个代码段中所显示的那样,您必须使用局部变量临时保留对您的Ad实例的引用,以便对其调用.save才能持久保存到数据库。 This should work: 这应该工作:

foo = Ad.find(2)
foo.user = User.find(1)
foo.save
Ad.find(2).user  # => #<User id: 1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM