用户名first_name字段创建一个full_name字段 [英] user first_name last_name fields to create a full_name field

查看:193
本文介绍了用户名first_name字段创建一个full_name字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前在我的模型中用rails表示的 first_name last_name 字段。我想在我的数据库中添加一个名为 full_name 的字段,并且想知道无缝完成这个操作的最佳方式是什么。请注意,我还有一台生产服务器,并且希望这样做,以便我不仅可以在迁移中添加列,还可以使用现有数据填充新字段。



编辑:

这里是我的控制器

  def followers 
@title =关注者
@user = User.find(params [:id])
@users = @ user.followers.paginate(page:params [:page])
@followers = @ user.followers.find(:all,:select =>'users.id,users.first_name,users.last_name',:conditions => [users.first_name like?, %+ params [:q] +%])

respond_to do | format |
format.html {render'show_follow'}
format.json {render:json => @followers}
end
end

我希望能够1。 select:'users.id,users.full_name 和2. :condition => [users.full_name like?,...] 并且我认为要做到这一点的唯一方法是修改模型。我也只想返回json对象中的属性 id full_name



在模型中定义一个full_name方法可能会更好:

def full_name
([first_name,last_name] - [''])。compact.join('')
end

您可以使用全名搜索:

  def self.find_all_by_name_containing(text)
self.where(LOWER(first_name ||''|| last_name)LIKE?,%#{text.downcase}%)
end

然后定义您自己的#to_json


I have first_name and last_name fields currently represented in my model in rails. I'd like to add another field to my database called full_name and was wondering what the best way to do this seamlessly would be. Mind you I also have a production server going and would like to make it so that I not only add a column in my migration, but also can populate the new field with the existing data.

EDIT:

Here's my controller

def followers
    @title = "Followers"
    @user = User.find(params[:id])
    @users = @user.followers.paginate(page: params[:page])
    @followers = @user.followers.find(:all, :select => 'users.id, users.first_name, users.last_name', :conditions => ["users.first_name like ?","%" + params[:q] + "%"])

    respond_to do |format|
      format.html {render 'show_follow'}
      format.json {render :json => @followers}
    end
end

I want to be able to 1. select: 'users.id, users.full_name and 2. :condition =>["users.full_name like ?", ...] and the only way I can think to do this is to modify the model. I also only want to return the properties id and full_name in the json object.

解决方案

You will probably be better off just defining a full_name method in your model:

def full_name                                                                                                                                                                                     
  ([first_name, last_name] - ['']).compact.join(' ')                         
end

You can search by full name with something like:

def self.find_all_by_name_containing(text)
  self.where("LOWER(first_name || ' ' || last_name) LIKE ?", "%#{text.downcase}%")
end

Then define your own #to_json

这篇关于用户名first_name字段创建一个full_name字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆