如何从选择框中访问ID?

时间:2011-10-04 20:54:06

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

我的表单中有一个选择框,其中包含数据库中的城市名称。当我选择一个城市并点击继续时,我希望它抓住所选的city_id并将我重定向到另一个页面(:controller=> 'people', action => 'index'),我将在那里使用city_id。我怎么做?我使用RAILS 3.这就是我所拥有的......

查看

 <%= form_for :cities, :url=>{:action =>"next"} do |f| %>
<%= collection_select(nil, :city_id, City.all, :id, :name ,:prompt=>"Select your city") %>
<%=f.submit "continue" %>
 <%end%>

控制器

class HomeController < ApplicationController
  def next
    @city = City.find(params[:city_id]) 
    redirect_to :controller => "people", :action => "index"
  end
  def new
    @city = City.new
  end
end

人员控制器

class PeopleController < ApplicationController
  def index
    @city = City.find(params[:city_id])
  end
end

1 个答案:

答案 0 :(得分:2)

您可以通过在next操作中设置会话变量来执行此操作:

class HomeController < ApplicationController
  def next
    @city = City.find(params[:city_id])
    session[:city_id] = @city.id
    redirect_to :controller => "people", :action => "index"
  end
  def new
    @city = City.new
  end
end

class PeopleController < ApplicationController
  def index
    unless session[:city_id].nil? || session[:city_id].blank?
      @city = City.find(session[:city_id])
      # do your stuff here
    end
  end
end

您也可以使用flash变量执行此操作,但会话可能是正确的位置。