Ruby on Rails:通过属性而不是id查找记录
我对rails非常陌生,所以请耐心等待我。
总之,我正在尝试创建一个表格,其中婚礼的客人可以输入简单的代码( invite_code
),然后回复。 from应该使用invite_code
,然后直接使用正确的invites#show
invite_code
视图。
到目前为止一切都那么好,但是我一直试图让轨道通过除了id
以外的东西找到记录,我想通过invite_code
找到。 假设我有一个id
为4且invite_id
为1234的invite_id
,当我输入’4’而不是’1234’时,表单找到了正确的记录。 这里有一些代码可以解释:
的routes.rb
get 'invites/search', to: 'invites#show', controller: :invites
形成
... ...
invites_controller
... def show if params.has_key?(:invite_code) @invite = Invite.find(params[:invite_code]) else @invite = Invite.find(params[:id]) end end ...
耙路线输出
Prefix Verb URI Pattern Controller#Action info_index GET /info/index(.:format) info#index invites GET /invites(.:format) invites#index POST /invites(.:format) invites#create new_invite GET /invites/new(.:format) invites#new edit_invite GET /invites/:id/edit(.:format) invites#edit invite GET /invites/:id(.:format) invites#show PATCH /invites/:id(.:format) invites#update PUT /invites/:id(.:format) invites#update DELETE /invites/:id(.:format) invites#destroy
invites_search GET /invites/search(.:format)邀请#show root GET / info #index
url示例
.../invites/search?utf8=%E2%9C%93&invite_code=1234 "utf8"=>"✓", "invite_code"=>"1234", "id"=>"search"
应用程序似乎忽略了invite_id
中if语句的invite_id
部分……
任何帮助表示赞赏,我花了很长时间才能做到这一点……
你有几个选择。 find_by_invite_code
会返回第一场比赛:
Invite.find_by_invite_code(params[:invite_code]) # First match or nil
虽然where
会给你所有的比赛作为数组
Invite.where(invite_code: params[:invite_code]) # Array of matches. May be empty
您还可以对find_by
使用以下语法:
Invite.find_by(invite_code: params[:invite_code]) # First match or nil
默认情况下find
使用id
字段where
改为使用where
if params.has_key?(:invite_code) @invite = Invite.where(invite_code: params[:invite_code]).first
... def show if params.has_key?(:invite_code) @invite = Invite.find_by(invite_code: params[:invite_code]) # find_by argument: value # returns first match or nil # same as find, where find searches by id # Invite.find_by_invite_code params[:invite_code] is deprecated else @invite = Invite.find params[:id] end end ...