Ruby on Rails saving two fields and combining them as a third -


i have authors model, has

first_name last_name full_name 

i need 3 because when searches author, need search through full names, when sort them, need sorted last name , can't separate them on space, because authors might have more 2 names.

so, in form user creates new author, have 2 entry fields - first_name , last_name. since adding third field full_name bad, , putting hidden field combines value of first/last names bad, wondering how can have 2 fields, on save combine values , save full_name column, without having field, hidden or not?

authors_controller.rb

class authorscontroller < applicationcontroller     def index         @authors = author.order(:last_name)         respond_to |format|             format.html             format.json { render json: @authors.where("full_name ?", "%#{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 

just add before_validation callback 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 generate , set full_name first_name , last_name when author saved.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -