2

我有一个可以正常工作的 simple_form ui,我f.input :group_ids用于将 Poll 分配给 Group(Poll has_and_belongs_to_many:groups,但我们将其限制为 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,但无法弄清楚如何将其限制为单选下拉菜单。

4

2 回答 2

2

您需要在方法createupdate中设置@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
于 2014-03-16T23:14:06.480 回答
0

我会尝试使用collection_select:

例如 f.collection_select(:group, :group_id, Group.all, :id, :name, :prompt => 'Group')

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

于 2012-08-10T03:19:17.850 回答