How come this works in the rails console:
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 . 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. 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
.
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. This should work:
foo = Ad.find(2)
foo.user = User.find(1)
foo.save
Ad.find(2).user # => #<User id: 1>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.