简体   繁体   中英

How to pass an id in URL to controller? Rails

I want to deal with some data rows with same key_id . I want them to get select by using an id in URL, so I will have /field_data/index/12 and 12 here means the key_id .

I can manually do it in the controller by hardcoding the key_id

def index 
    @key_id = 12
    @field_data = FieldDatum.select('field_content').where("key_id = ?", @key_id)
end

and my URL is very general: /field_data

So how to make it be able to get the id in URL?

routes

get "/field_data/index/:key_id", to: "field_datas#index"

controller

def index 
  @field_data = FieldDatum.select('field_content').where(key_id: params[:key_id])
end

Try this:

Show.html.erb

<% user_all.each do |user| %>
   <%= link_to user_id_pass_path(user.id), method: :get do %>
    <span class="btn btn-warning">Pass Id</span>
   <% end %>
<% end %>

routes.rb

 get '/user_id_pass/:id' => 'users#user_id_pass', as: 'user_id_pass'

users_controller.rb

 def user_id_pass
   @user = User.find_by_id(params[:id])
 end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM