I am using Active record 5 in my custom Ruby script.
(Controller/Rake task)
books.each do |book|
b_id = book[“b_id”]
bk = Books.where(book_id: b_id).first
bk = Books.new(book_id: b_id) unless bk
bk.update_book_info(book)
if bk.changed?
# ...send book title to Api...
bk.save!
end
end
(Model)
class Book < ActiveRecord::Base
before_save :get_title
def update_book_info(book)
@book = book
end
private
def get_title
# do ..something
self.title = @book[’title’]
end
end
books
is an array.
Please note the [...send book title to Api...]
part. I need to know the book title so that I can send it to API. I have tried bk.title
but it returns null
!
How to get the book title ?
Also, can I move more code from controller to model?
Help :)
If it returns nil
... Then it is empty. Check the object in your rails console. In your terminal, run:
rails c
Then:
Book.first # see the whole object
Book.first.title # see its title
Book.all.pluck(:title) # see all the titles in the database
You might want to check where you save your books if there isn't something wrong which would cause the title not to be saved.
Side note: in your code, you're doing some unnecessary queries. In your each
loop, you're querying the database for an object your already have. This line:
bk = Books.where(book_id: b_id).first # useless query
Is going to return the same book
object from which you extracted the id
. Also, when looking for an object with an id, no need to use where
since an id is unique, it can only return one object. Use #find
or #find_by
.
Instead create the method #update_book_info
you could use #assign_attributes(new_attributes)
like this:
bk.assign_attributes(book)
It will guarantee that your model will be dirt and the #changed?
method will work. Also, your bk#title
will be loaded before the #save
, which seems to be what you want.
Then you will be able to remove the before_save
and #get_title
as well.
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.