ruby-on-rails Ruby on Rails:按属性而不是ID查找记录

41ik7eoe  于 2022-11-26  发布在  Ruby
关注(0)|答案(3)|浏览(210)

我对Rails还很陌生,所以请耐心等待。
简而言之,我试图创建一个表单,参加婚礼的客人可以在其中输入一个简单的代码(invite_code),然后RSVP。from应该接受invite_code,然后直接使用正确的invites#show视图。
到目前为止一切顺利,但是我一直在尝试让rails查找除和id之外的记录,我想查找invite_code。假设我有一个Invite,其中id为4,invite_id为1234,当我在from中输入“4”而不是“1234”时,窗体正在查找正确的记录。下面是一些代码来解释:

路由.rb

get 'invites/search', to: 'invites#show', controller: :invites

表格

...
<%= form_tag invites_search_path, method: :get do %>
  <%= label_tag :invite_code, "#" %>
  <%= text_field_tag :invite_code, nil %>
  <%= submit_tag "Search", name: nil %>
<% end %>
...

邀请控制器

...
  def show
    if params.has_key?(:invite_code)
      @invite = Invite.find(params[:invite_code])
    else
      @invite = Invite.find(params[:id])
    end
  end
...

rake路由输出

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

请输入您的搜索请求,并输入您的搜索结果。

URL示例

.../invites/search?utf8=%E2%9C%93&invite_code=1234

"utf8"=>"✓", "invite_code"=>"1234", "id"=>"search"

应用程序似乎忽略了控制器中if语句的invite_id部分...
我花了很长时间才走到这一步...

cygmwpex

cygmwpex1#

您有几个选项。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
vshtjzan

vshtjzan2#

默认情况下,find使用id字段,请改用where

if params.has_key?(:invite_code)
  @invite = Invite.where(invite_code: params[:invite_code]).first
0x6upsns

0x6upsns3#

...
  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
...

相关问题