Rails选择表单未在重定向

时间:2016-05-04 00:42:31

标签: jquery ruby-on-rails ajax google-maps

我正在创建一个包含城市评论的网站(yay标准CRUD应用程序!),使用@cities_array实例变量填充所有可用城市的表单。在reviews_controller中查看我的新方法:

  def new
    @review = Review.new
    @cities_array = City.cities_alphabetized
  end

用户访问new_review_path,表单下拉列表中填充了应有的城市,一切都很好。表格代码:

<%= f.select :city_id, options_for_select(@cities_array) %>

在同一页面上,还有另一种形式,如果用户不在下拉列表中,则可以添加城市。他们输入名称,并向Google Geocoder发送一个AJAX请求,该请求路由到我的创建城市方法并创建新城市。创建方法:

def create
    latitude = params[:latitude].to_f.round(4)
    longitude = params[:longitude].to_f.round(4)
    name = params[:name]
    city = City.new(name: name, latitude: latitude, longitude: longitude)
    if city.save
      flash[:success] = "City created! Please refresh."
      redirect_to new_review_path
    else
      flash[:notice] = "Your city couldn't be created."
      redirect_to new_review_path
    end
  end

您会注意到,如果保存新城市,则会将用户重定向到评论页面。但是,除非用户手动刷新浏览器,否则我的城市下拉列表不会更新。

为什么重定向后这个表单没有刷新?我查了一下,我的@cities_array正在递增以包含新城市,但为什么用户必须刷新新城市以显示在表单的下拉列表中?

显然我不理解那里的东西!

以下是有用的日志:

Started POST "/cities" for ::1 at 2016-05-03 21:11:49 -0400
Processing by CitiesController#create as HTML
  Parameters: {"name"=>"Dong Hoi", "latitude"=>"21.0128173", "longitude"=>"107.45755380000003"}
   (0.2ms)  BEGIN
  SQL (0.6ms)  INSERT INTO "cities" ("name", "latitude", "longitude", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["name", "Dong Hoi"], ["latitude", 21.0128], ["longitude", 107.4576], ["created_at", "2016-05-04 01:11:50.021635"], ["updated_at", "2016-05-04 01:11:50.021635"]]
   (0.6ms)  COMMIT
Redirected to http://localhost:3000/reviews/new
Completed 302 Found in 33ms (ActiveRecord: 6.3ms)


Started GET "/reviews/new" for ::1 at 2016-05-03 21:11:50 -0400
Processing by ReviewsController#new as HTML
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  City Load (1.1ms)  SELECT "cities".* FROM "cities"
  Rendered reviews/new.html.erb within layouts/application (11.2ms)
Completed 200 OK in 442ms (Views: 176.8ms | ActiveRecord: 5.3ms)

2 个答案:

答案 0 :(得分:0)

我认为您需要的是在提交表单后显示所选值。试试这个:

<%= f.select :city_id, options_for_select(@cities_array, selected: @review.city_id) %>

请告诉我这是否适合您。

答案 1 :(得分:0)

是的,我的意思是Ajaxing。你也可以尝试一下,让我知道:

if city.save
  flash[:success] = "City created! Please refresh."
  @cities_array = City.cities_alphabetized
  render :new
else
  flash[:notice] = "Your city couldn't be created."
  redirect_to new_review_path
end