Question

Could you please show how form should look for has_many :through association?

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

But I have some doubts about _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 %>

What is the best way to add Users for a new Event?

Thanks in advance!

Was it helpful?

Solution

Instead of

<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>

You could try:

<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>

OTHER TIPS

Just found more elegant solution:

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>

more you can find here: http://railscasts.com/episodes/258-token-fields-revised

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top