如何从链接访问ID?

时间:2011-10-12 02:38:07

标签: ruby-on-rails ruby-on-rails-3 rails-routing

我正在显示数据库中的城市列表,每个都是链接。我想当用户点击任何一个城市时,操作会通过抓住该城市的ID并在下一个操作中重新使用它来显示(显示在这种情况下的行动)。那你如何从链接中获取一个id?下面是我的想法,它没有用。提前谢谢你。

查看/城市

    <%@cities.each do |city| %>
    <a href="/deal/city"><%=city.name%></a><br/>
    <%end%>

控制器

   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? || session[:city_id].blank?
   @city = City.find(session[:city_id])
   @deals=@city.deals
   end

   end

路由

    get "deal/city"
    match 'deal/city'  => "deal#city"

1 个答案:

答案 0 :(得分:1)

您没有在链接中传递city_id。尝试:

<% @cities.each do |city| %>
    <a href="/deal/city?city_id=<%= city.id %>"><%= city.name %></a><br/>
<% end %>

如果您希望链接类似于“/ deal / city / 1”并获得1作为params[:city_id],则可以像这样修改您的路线:

match 'deal/city/:city_id'  => "deal#city", :via => :get

并使用以下链接:

<% @cities.each do |city| %>
    <a href="/deal/city/<%= city.id %>"><%= city.name %></a><br/>
<% end %>