RubyonRails保存了两个字段,并将它们组合为第三个字段



我有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

只需在Author模型中添加一个before_validation回调:

# 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

在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], ..)

最新更新