【问题标题】:simple_form association input switches from drop-down/select to text input upon failed validationsimple_form 关联输入在验证失败时从下拉/选择切换到文本输入
【发布时间】:2012-08-10 02:57:46
【问题描述】:

我有一个可以正常工作的 simple_form ui,我正在使用 f.input :group_ids 将轮询分配给组(轮询 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,但不知道如何将其限制为单选下拉菜单。

【问题讨论】:

  • 希望有一种方法可以在 simple_form 中执行此操作,但现在我只使用 f.select github.com/codeforamerica/textizen/commit/…
  • 事实证明,提交的另一部分解决了这个问题——传入@groups 变量来更新和创建,而不仅仅是新建和编辑。恢复为 simple_form 并且工作正常。

标签: ruby-on-rails ruby-on-rails-3 erb simple-form


【解决方案1】:

您需要在渲染操作 new 之前在方法 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

【讨论】:

    【解决方案2】:

    我会尝试使用 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-01-06
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      相关资源
      最近更新 更多