has_many的形式:通过

时间:2014-02-19 14:27:54

标签: ruby-on-rails ruby-on-rails-4 nested-forms has-many-through

请问你能说明一下表单应该如何查找has_many:通过关联吗?

user.rb

has_many :participations
has_many :events, :through => :participations

event.rb

  has_many :participations
  has_many :users, :through => :participations

  accepts_nested_attributes_for :participations

participations.rb

  belongs_to :user
  belongs_to :event

events_controller.rb

  def new
    @event = Event.new
    @participation = @event.participations.build
  end

  def create
    @event = Event.new(params[:event].permit!)

    respond_to do |format|
      if @event.save
        format.html { redirect_to events_path, notice: 'Event was successfully created.' }
      else
        format.html { render action: 'new' }
      end
    end
  end

但我有些疑惑 的 _form.html.erb

<%= form_for @event, :html => {:class => 'row'} do |f| %>

    <div class="form-group">
      <%= f.label :name, :class => 'control-label' %><br>
      <%= f.text_field :name, :class => 'form-control' %>
    </div>

    <div class="form-group">
      <%= f.label :description, :class => 'control-label' %><br>
      <%= f.text_area :description, :class => 'form-control' %>
    </div>

    <div class="form-group">
      <%= f.fields_for :participations do |f_p| %>
        <%= f_p.label :user_ids, "Users" %>
        <%= f_p.select :user_ids, options_from_collection_for_select(User.all, :id, :name), { :multiple => true } %>
      <% end %>
    </div>


    <div class="actions">
      <%= f.submit 'Save', :class => 'btn btn-default' %>
    </div>

<% end %>

为新活动添加用户的最佳方式是什么?

提前致谢!

2 个答案:

答案 0 :(得分:2)

而不是

<div class="form-group">
  <%= f.fields_for :participations do |f_p| %>
    <%= f_p.label :user_ids, "Users" %>
    <%= f_p.select :user_ids, options_from_collection_for_select(User.all, :id, :name), { :multiple => true } %>
  <% end %>
</div>

你可以尝试:

<div class="form-group">
   <% User.all.each do |user| %>
    <%= check_box_tag 'event[user_ids]', user.id, @event.user_ids.include?(user.id) -%>
   <%= label_tag user.name %>
  <% end %> 
</div>

答案 1 :(得分:0)

刚刚找到更优雅的解决方案:

<强> form.html.erb

<div class="form-group">
  <%= f.label :user_ids, "Participants" %><br>
  <%= f.collection_select :user_ids, User.order(:name), :id, :name, {}, {:multiple => true} %>
</div>

您可以在此处找到更多内容:http://railscasts.com/episodes/258-token-fields-revised