0

Im trying to make so that if someone make a post without a title the post will get a default title.

I have tried this so far

controller

def create
@post = Post.create(post_params)
  if @post.title.nil?
    @post.update(:title => 'Unnamed')
  else
    # DO NOTHING
  end
end

controller

def create
  if params[:title].nil?
    params[:title] == 'Unnamed'
    @post = Post.create(post_params)
  else
    @post = Post.create(post_params)
  end
end

But it dosen't work. Any ideas what im doing wrong? Thanks in advance.

niiicolai
  • 73
  • 2
  • 12

3 Answers3

6

I my opinion it is the models responsiblity to keep itself in a valid state. Furthermore it is the best solution according to DRY principles if multiple controllers change of update the same model. Therefore I would do something like this in the Post model:

before_validation :set_default_title

private
def set_default_title
  self.title = title.presence || 'Unnamed'
end
spickermann
  • 100,941
  • 9
  • 101
  • 131
1

It seems you are processing strong parameters and so it doesn't work to set default title to params after permit all attributes.

def post_params
  params[:post][:title] = "Unnamed" if params[:post][:title].blank?
  #params.require(:post).permit(:title, ...)
end

Post.create(post_params)

I also recommend to use blank?. Here are differences between blank?, empty? and nil?.

nil.nil? => true
"".nil? => false
"   ".nil? => false

nil.empty? => true
"".empty? => true
"   ".empty? => false

nil.blank? => true
"".blank? => true
"   ".blank? => true
bhugo313
  • 431
  • 2
  • 6
0

I understand that you don't want a default value for the title to be displayed in the input field. Maybe this solution can work

  def create
    @post = Post.new(post_params)
    @post.title = @post.title.presence || 'Unnamed' 

    if @post.save
      redirect_to # ...
    else
      render :new
    end
  end

Or a before_validation filter in your model can do the job.

Benjamin J. Benoudis
  • 1,101
  • 11
  • 22