从Rails中的collection_select中选择所有或单个对象

时间:2012-10-12 14:21:05

标签: ruby-on-rails-3 forms activerecord select

我有一个通过actionmailer发送“页面”的应用。在我的视图代码中,我设置了一个特定的单元,然后分配了医生,他们获得了电子邮件/页面。我想在我的select语句中包含一个选项来分页所有单元,但我不知道该怎么做。

查看/表单代码:

<%= form_for(@page) do |f| %>

  <%= f.label :message %>
  <%= f.text_field :message %>

  <%= f.label 'Medic'%>

  <%= f.collection_select(:unit_id, Unit.order("unit_name ASC"), :id, :unit_name, {}, {:class => 'select'})%>

<%= f.button :send, :class => 'btn btn-info' %>

<% end %>

控制器代码:

def create

    @page = Paging.new(params[:paging])
    unit = Unit.find(params[:paging][:unit_id])
    message = params[:paging][:message]


     if @page.save
       PagingsMailer.paging(unit.incharge, unit, message).deliver
       PagingsMailer.paging(unit.attendant, unit, message).deliver
       redirect_to pagings_path, notice: "Page was successfully sent."
      else
        redirect_to pagings_path
     end
  end

只要原始选择被忽略,该选项可以在选择本身或另一个选择/复选框中。

对此有任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

我得到了一些帮助,并且能够通过在表单中​​创建一个数组数组并将“all”传递给控制器​​来执行单个邮件来解决它。

查看代码:

<%= f.select :unit_id, options_for_select(Unit.order.map{ |unit| [unit.unit_name, unit.id] } + [["All Medics", "all"]]), {}, {:class => 'select'} %>

控制器代码:

def create
    message = params[:paging][:message]

    if params[:paging][:unit_id] == "all"
      Unit.all.each do |unit|
        @page = Paging.new(params[:paging])
        @page.unit_id = unit.id

        if @page.save
          PagingsMailer.paging(unit.incharge, unit, message).deliver
          PagingsMailer.paging(unit.attendant, unit, message).deliver
          flash.notice = "Page was successfully sent."
        end
      end
    else
      @page = Paging.new(params[:paging])
      unit = Unit.find(params[:paging][:unit_id])

      if @page.save
        PagingsMailer.paging(unit.incharge, unit, message).deliver
        PagingsMailer.paging(unit.attendant, unit, message).deliver
        flash.notice = "Page was successfully sent."
      end
    end