0

I am trying to follow the episode #258 Token Fields (revised). I don't know how the code create authors, I have a feeling that is related to the code below, but I am not sure.

Please can you explain how the code create authors?

in /app/models/book.rb

def author_tokens=(tokens)
    self.author_ids = Author.ids_from_tokens(tokens)
end

Link to episode http://railscasts.com/episodes/258-token-fields-revised?view=asciicast

Thanks!

dinnouti
  • 1,707
  • 2
  • 15
  • 21

1 Answers1

1

This code doesn't actually create the author. The authors themselves need to already be created. This code will take the author's tokens, and turn those into IDs. So the Book will have many authors.

You can see in this image below, the authors already exist as the book is being created. We are selecting from the book

choosing image

image credit: http://railscasts.com/episodes/258-token-fields-revised?view=asciicast

UPDATE

In the end of the episode, the system will create new authors if one is not found. This is created by this code: https://github.com/railscasts/258-token-fields-revised/blob/master/bookstore-tokeninput-after/app/models/author.rb

  class Author < ActiveRecord::Base
    ##...
    def self.ids_from_tokens(tokens)
      tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
      tokens.split(',')
    end
  end

So, if the tokens come in with <<>> (which gets sent from the Author.tokens method), it will create the author and then get the ID and return it.

Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109
  • In the very bottom of the page Ryan Bates show how to add a new Authors using the token field - http://asciicasts.com/system/photos/1161/original/E258I08.png – dinnouti Jan 24 '13 at 07:11
  • I see the disconnect, in the asciicast it does not show the **def self.ids_from_tokens(tokens)**. Thanks for helping out. – dinnouti Jan 24 '13 at 14:14