Rails 动态下拉列表未在编辑表单中预先填充

发布于 2024-12-03 23:24:44 字数 1116 浏览 3 评论 0原文

我在用户表单中有一个动态下拉菜单,其中包含基于所选州的城市。该表单在创建记录时工作正常,但在编辑用户时,仅使用现有值填充州 - 理想情况下,表单将填充用户的州和城市(州的城市填充在下拉列表中)。

在表单中,我有:

<%= f.input :state_id, :collection => @states, :prompt => "Pick Your State" %>
</div>    
<div id="usercities">
  <%= render :partial => 'cities', :locals => { :cities => @cities, :user => form } %>
</div>

在部分我有:

<%= simple_fields_for :user do |fields| %>
  <% if cities.blank? %>
    <%= fields.input :city_id, :collection => cities, :prompt => "Pick Your State" %>
  <% else %>
<%= fields.input :city_id, :collection => cities, :prompt => "Pick Your City" %>
  <% end %>
<% end %>

在控制器中

    @states = State.where(:active => true)
    @cities = City.where(:active => true, :state_id => [@user.state_id])

当我编辑表单时,城市下拉列表为空,但如果我更改状态,它就会正确填充城市

谢谢

编辑:

不确定是否相关,但在routes.rb中我有 匹配 'users/update_city_select/:id', :controller=>'users', :action => '更新城市选择'

I have a dynamic drop-down in a user form that contains cities based on the selected state. The form works perfectly when creating the record, but when editing the user, only the state is populated with the existing value - ideally, the form would be populated with the user's state and city (with the state's cities populated in the drop-down.

In the form, I have:

<%= f.input :state_id, :collection => @states, :prompt => "Pick Your State" %>
</div>    
<div id="usercities">
  <%= render :partial => 'cities', :locals => { :cities => @cities, :user => form } %>
</div>

In the partial I have:

<%= simple_fields_for :user do |fields| %>
  <% if cities.blank? %>
    <%= fields.input :city_id, :collection => cities, :prompt => "Pick Your State" %>
  <% else %>
<%= fields.input :city_id, :collection => cities, :prompt => "Pick Your City" %>
  <% end %>
<% end %>

In the controller

    @states = State.where(:active => true)
    @cities = City.where(:active => true, :state_id => [@user.state_id])

When I am editing the form, the cities drop-down is blank, but if I change the state, it becomes populated with the cities correctly.

Thanks!

edit:

not sure if it's relevant, but in the routes.rb I have
match 'users/update_city_select/:id', :controller=>'users', :action => 'update_city_select'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

合约呢 2024-12-10 23:24:44

也许控制器的 edit 方法没有填充 @cities

尝试添加您在 new 上的行,如果不起作用,请在部分中添加 <%= raise cars.inspect %> 以查看内容。

Maybe the edit method of the controller is not populating the @cities.

Try adding the line you have on the new, and if not working put a <%= raise cities.inspect %> in the partial to see the contents.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文