views:

73

answers:

1

Hi, I have a simple module for adding the current user to a newly created object:

module AttachUsers

  def create_with_author(author, params)
    created = new(params)
    created.author = author
    created.save
    created
  end

  def create_with_author_and_editor(author, params)
    created = new(params)
    created.author = author
    created.lasteditor = author
    created.save
    created
  end

end

The module is saved as attach_users.rb directly under the lib directory.

I've tried to use this module with two models so far. It worked fine with the first (comment) model, however the second (page) returns the error message

undefined method `create_with_author_and_editor'

I have the following at the top of each of my models:

extend AttachUsers

I am using it in the comments controller like this:

@comment = @post.comments.create_with_author(current_user, params[:comment])

And in the pages controller like this:

@page = Page.new
respond_to do |format|
if @page.create_with_author_and_editor(current_user, params[:page])

Can anyone see why it might not be working correctly? This is the first time I've tried to use modules, sorry if it's something obvious.

Any advice appreciated.

Thanks

+2  A: 

Try using include AttachUsers instead of extend AttachUsers.

Also, this is not the way I'd do this. You might be better off using association extensions.

module CreateWithAuthorAndEditor
  def create_with_author(author, params)
    create(params.merge({ :author => author })
  end
end

class Post< ActiveRecord::Base
  has_many :comments :extend => CreateWithAuthorAndEditor
end

Then you can call:

post.comments.create_with_author(current_user, params[:comment])
jonnii
Thanks. I'd not heard of those before. I'll check them out!
Dan
I'm not sure, it's hard to tell what your code is doing in a comment.
jonnii
@Dan, Just FYI, `extend` effectively adds the methods as class methods, `include` adds the methods as instance methods. So if you wanted `Page.create_with_author_and_editor` you'd want to use `extend`.
Tim Snowhite