Ruby on Rails的:由一个属性不是ID查找记录(Ruby on Rails: Find a

2019-10-21 13:26发布

我很新的轨道,所以请耐心等待我。

总之我想创造一个客人婚礼可以输入简单的代码(如表格invite_code ),然后RSVP。 该从应采取invite_code ,然后采取使用直正确的invites#show视图。

到目前为止好,但我坚持试图让导轨找到比其他的东西,记录id ,我想找到invite_code 。 说我有一个Inviteid的4和invite_id的1234,当我输入“4”进入从但不是“1234”的形式是找到正确的记录。 下面是一些代码来解释:

的routes.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 %>
...

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)邀请展#根GET / INFO#指数

URL例子

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

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

该应用程序似乎忽略invite_id if语句中的控制器部分...

任何帮助表示赞赏,这是我花了很长时间远远得到这个...

Answer 1:

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


Answer 2:

find使用id默认域,使用where代替

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


Answer 3:

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


文章来源: Ruby on Rails: Find a record by an attribute not an id