2

能否請您展現形式應該如何尋找的has_many:通過關聯?表格的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 %> 

什麼是用戶添加新事件的最好方式有些疑惑?

在此先感謝!取而代之的

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

回答

2

你可以嘗試:

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

啊,非常感謝你!這正是我正在尋找的! – MikeAndr

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