我有一个工作正常的 simple_form ui,我正在使用 f.input :group_ids
将轮询分配给一个组(轮询 has_and_belongs_to_many
:groups,但我们将其限制为用户界面中的一个)。
无论如何,我想要一种更优雅的方式来完成 UI,但是当验证失败时,它也会导致严重的问题——输入恢复为带有值的文本输入:[4],其中 4 是当前的 id团体。 (除了看起来很糟糕之外,除非手动删除括号,否则提交会失败)
<%= simple_form_for @poll do |f| %>
<% if params[:group] %>
<%= f.input :group_ids, :label => "Group", :selected => params[:group], :collection => @groups, :include_blank => false, :input_html => {:multiple => false} %>
<% else %>
<%= f.input :group_ids, :label => "Group", :collection => @groups, :include_blank => false, :input_html => {:multiple => false} %>
<% end %>
...
<% end %>
我希望有一种更好的方法来做到这一点 - 尝试使用 f.association,但无法弄清楚如何将其限制为单选下拉列表。
最佳答案
您需要在渲染操作new或之前在方法create或update中设置@groups分别编辑
例如
def new
@groups = Group.all
....
end
def create
@poll = Poll.new(poll_params)
respond_to do |format|
if @poll.save
format.html { redirect_to ... }
format.json { render action: 'show', status: :created, location: @poll }
else
### ! in case of validation is failed init data for the form ! ###
@groups = Group.all
format.html { render action: 'new' }
format.json { render json: ... }
end
end
end
关于ruby-on-rails - simple_form 关联输入在验证失败时从下拉/选择切换到文本输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11894867/