petrov
petrov

Reputation: 57

Using service classes in rails application

So, I created app/services folder and then some classes inside with .call methods(I am trying to understand the logic of the services and query objects)

app/services/add_comment_to_post.rb

class AddCommentToPost
  def initialize(post:, comment:)
    @post = post
    @comment = comment
  end

  def call
    @post.comments.create(@comment)
    @post
  end
end


app/services/remove_comment_from_class.rb

class RemoveCommentFromPost
  def initialize(post:, comment:)
    @post = post
    @comment = comment
  end

  def call
    @[email protected]
    @post
  end
end

and in the comments_controller.rb

     def create
        #this one works:
        #@post.comments.create! comment_params

        AddCommentToPost.new(@post, @comment).call
        redirect_to @post


     def destroy
         RemoveCommentFromPost.new(@post,@comment).call
         redirect_to @post

Can anybody tell me what should I change to make it works, or where to look for similar examples? The posts and comments are scaffolded, and I use nested routes.

Rails.application.routes.draw do

  resources :posts do
    resources :comments
  end

  root "posts#index"

end

Upvotes: 2

Views: 816

Answers (1)

Derek Prior
Derek Prior

Reputation: 3517

In general, it's helpful if you include the error you're getting from what you've tried. In this case, I've scanned the code and noticed a couple of errors that you should correct.

Your service objects define their initialize method to take keyword arguments like so:

def initialize(post:, comment:)
  @post = post
  @comment = comment
end

But you are initializing them by passing positional arguments like so:

AddCommentToPost.new(@post, @comment).call

You should initialize them with the expected keyword arguments like so:

AddCommentToPost.new(post: @post, comment: @comment).call

Additionally, as pasted above, your destroy method:

def destroy
  RemoveCommentFromPost.new(@post,@comment).call
  redirect_to @post

is missing an end.

Finally, you'll still want to check the return value of those service object calls to determine if the call succeeded or failed and handle appropriately. You are currently redirecting regardless.

Upvotes: 2

Related Questions