How do i access an id from the link?
I am displaying list of cities from the database ,each as a link.I want when a user click on any of the cities ,the action respond by grabbng the id of that city and re use it on the next action(show action in this case).So How do you grab an id from the link?Below is my idea which didnt work.Thank you in advance.
View/cities
<%@cities.each do |city| %>
<a href="/deal/city"><%=city.name%></a><br/>
<%end%>
Controller
Class DealController < ApplicationController
def all_cities
@cities=City.find(:all)
end
def city
@city=City.find(params[:city_id])
session[:city_id] = @city.id
redirect_to :controller=>"deal",:action=>"show"
end
def show
unless session[:city_id].nil? || 开发者_StackOverflowsession[:city_id].blank?
@city = City.find(session[:city_id])
@deals=@city.deals
end
end
routes
get "deal/city"
match 'deal/city' => "deal#city"
You are not passing the city_id
in the link. Try:
<% @cities.each do |city| %>
<a href="/deal/city?city_id=<%= city.id %>"><%= city.name %></a><br/>
<% end %>
If you want the link to be like "/deal/city/1" and get 1 as params[:city_id]
, you can modify your routes like this:
match 'deal/city/:city_id' => "deal#city", :via => :get
and use the link like this:
<% @cities.each do |city| %>
<a href="/deal/city/<%= city.id %>"><%= city.name %></a><br/>
<% end %>
精彩评论