Wins Lin <[email protected]> wrote: > Could you please explain me (of course if you know) how this code in the > engine works. This is an example from Rails Engine tutorial > (http://edgeguides.rubyonrails.org/engines.html#using-a-class-provided-by-the-application): > > > attr_accessor :author_name > belongs_to :author, class_name: "User" > > before_save :set_author > > private > def set_author > self.author = User.find_or_create_by(name: author_name) > end > > > I cannot understand how "author_name" parameter appears in the model. > "author_name" parameter doesn't belong to model. It is from params, from > a form. So somehow it has to be passed to the model. But how? > > attr_accessor is not attr_accessible. Why is it there? What does it > mean? > > > The table "posts" for the model Post is as follows: > --------------------------------- > | id | title | text | author_id | > --------------------------------- > > > So, the new @post has to be created this way: > > @author = User.new(...some params...) > @post = Post.new(:title => "title", :text => "text", :author_id => > @author.id) > @post.save! > > But there is some "set_author" method. What is a magic is it with that > "set_author" method and :author_name parameter?
Hummm, no. @post = Post.new(:title => "title", :text => "text", :author_name => "Wins Lin") @post.save! see the author_name up there? When you save the post, that's when it calls the #set_author method, which either finds an existing author with the name given, or creates a new one, which is connected to the new post record with self.author. When the save actually happens, AR is smart enough to know to hook up self.author.id with author_id in the Post table. You *can* do it the other way around, but it's clearly more work, since ActiveRecord/Arel is doing all that for you. -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/51b5bab0.a41db60a.1e4b.1910%40mx.google.com?hl=en-US. For more options, visit https://groups.google.com/groups/opt_out.

