【问题标题】:Ruby on Rails saving two fields and combining them as a thirdRuby on Rails 保存两个字段并将它们组合为第三个字段
【发布时间】:2014-11-12 11:38:55
【问题描述】:

我有 Authors 模型,它有

first_name
last_name
full_name

我需要这三个,因为当有人搜索作者时,他们需要搜索全名,但是当我对它们进行排序时,它们需要按姓氏排序,我不能只用空格将它们分开,因为有些作者可能有两个以上的名字。

因此,在用户创建新作者的表单中,他们有两个输入字段 - first_name 和 last_name。由于为 full_name 添加第三个字段非常糟糕,并且放置一个结合了名字/姓氏值的隐藏字段几乎同样糟糕,我想知道如何才能只有两个字段,但在保存时合并它们的值并保存到 full_name 列,没有额外的字段,隐藏与否?

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    只需将before_validation 回调添加到您的Author 模型:

    # in author.rb
    before_validation :generate_full_name
    
    ...
    
    private
    def generate_full_name
      self.full_name = "#{first_name} #{last_name}".strip
    end
    

    当保存Author 时,此回调将从first_namelast_name 生成并设置full_name

    【讨论】:

    • 正是我一直在寻找的!
    【解决方案2】:

    在 author.rb(模型文件)中定义一个创建函数:

    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
    

    在你的控制器中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2015-11-10
      • 2020-02-20
      相关资源
      最近更新 更多