Rails 动态下拉列表未在编辑表单中预先填充
我在用户表单中有一个动态下拉菜单,其中包含基于所选州的城市。该表单在创建记录时工作正常,但在编辑用户时,仅使用现有值填充州 - 理想情况下,表单将填充用户的州和城市(州的城市填充在下拉列表中)。
在表单中,我有:
<%= 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许控制器的
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.