0
votes

I have Authors model, which has

first_name
last_name
full_name

I need all three because when someone searches for an author, they need to search through the full names, but when I sort them, they need to be sorted by the last name and I can't just separate them on space, because some authors might have more than two names.

So, in the form where a user creates a new author, they have two entry fields - first_name and last_name. Since adding a third field for full_name is simply bad, and putting a hidden field that combines the value of first/last names is almost as bad, I was wondering how can I have only two fields, but on save combine their values and save that to the full_name column, without having an extra field, hidden or not?

authors_controller.rb

class AuthorsController < ApplicationController
    def index
        @authors = Author.order(:last_name)
        respond_to do |format|
            format.html
            format.json { render json: @authors.where("full_name like ?", "%#{params[:q]}%") }
        end
    end

    def show
        @author = Author.find(params[:id])
    end

    def new
        @author = Author.new
    end

    def create
        @author = Author.new(params[:author])
        if @author.save
            redirect_to @author, notice: "Successfully created author."
        else
            render :new
        end
    end
end
2

2 Answers

1
votes

Just add a before_validation callback to your Author model:

# in author.rb
before_validation :generate_full_name

...

private
def generate_full_name
  self.full_name = "#{first_name} #{last_name}".strip
end

This callback will generate and set the full_name from the first_name and last_name when the Author is saved.

0
votes

In author.rb (model file) define a create function:

def self.create(last_name, first_name, ...)
  full_name = first_name + " " + last_name
  author = Author.new(:last_name => last_name, :first_name => first_name, :full_name => fullname, ...)
  author.save
  author
end

In your controller

Author.create(params[:last_name], params[:first_name], ..)