我有一个simple_form ui工作正常,我正在使用f.input :group_ids
为一个组分配一个民意调查(民意调查has_and_belongs_to_many
:群组,但我们将其限制在UI中只有一个)。
我想要一个更优雅的方式来执行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,但无法弄清楚如何将其限制为单选下拉列表。
答案 0 :(得分:2)
在呈现操作新或之前,您需要在方法创建或更新中设置 @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
答案 1 :(得分:0)
我会尝试使用collection_select:
e.g。像f.collection_select(:group,:group_id,Group.all,:id,:name,:prompt =&gt;'Group')等事情