Alexander
Alexander

Reputation: 139

Is it correct architecture for adding user's posts?

Create action in posts controller:

  def create
    @post = current_user.posts.build(post_params)
    if @post.not_exists?(current_user)
      if @post.save
        #flash
        redirect_to root_path
      else
        #flash[:error]
        redirect_to root_path
      end
    else
      #flash[:error]
      redirect_to root_path
    end
  end

Post model:

class Post < ActiveRecord::Base
  belongs_to :user

  ##validations


  def not_exists?(user)
    return true unless user.posts.find_by(name: self.name)
  end

end

My question: is it correct to build my create action like this? Or there is a better architectural design? I think it is too fat action.

Upvotes: 1

Views: 29

Answers (1)

jazzytomato
jazzytomato

Reputation: 7214

Why not use a validation instead ?

class Post < ActiveRecord::Base
  belongs_to :user

  validates_uniqueness_of :name, :scope => :user_id

Upvotes: 1

Related Questions