I’m trying to make a chainable method such that I can write:
@blog = Blog.new.set_user(current_user).save
instead of
@blog = Blog.new
@blog.user = current_user
I have defined the following method inside the model:
def set_user(user)
self.user = user
return self
end
except that it doesn’t work. How do I make a method to return the updated instance so that further chaining can be done upon it?
UPDATE:
My bad, here’s what I was doing wrong: The chainable method was named “user” and so it was conflicting with the model’s own blog.user method. I changed the name to something unique and voila! it works.
I would try to avoid this in Rails and use the models associations and scopes to do part of the work:
About the question you asked, returning self should do the work idd, can you write the output of the console when you create the blog and also let us know what is the output of:
Maybe the error is somewhere else…