RobertJoseph
RobertJoseph

Reputation: 8158

How to construct a Rails for a many-to-many model?

I have a User, a Wiki, and a Collaborator model:

class User < ActiveRecord::Base
  has_many :wikis
  has_many :collaborators
end

class Wiki < ActiveRecord::Base
  has_many :wikis
  has_many :collaborators
end

class Collaborator < ActiveRecord::Base
  belongs_to :user
  belongs_to :wiki
end

When I am editing a Wiki's collaborators I would like the form to look something like this: enter image description here

My problem is that I cannot figure out how to construct the form. I thought the following would work but <% form_for :collaborator do |f|%> doesn't result in anything being included in the resulting page.

<% form_for :collaborator do |f|%>
    <% possible_collaborators.each do |user| %>
        <%= check_box_tag 'wiki[collaborator_ids][]', user.id, wiki.collaborators.include?(user) %>
        <%= user.name %> 
        <br />
    <% end %>
    <%= f.submit %>
  <% end %>

Upvotes: 1

Views: 33

Answers (1)

smallbutton
smallbutton

Reputation: 3437

As you didn't post your controller code I can't be entierly sure what you are trying to accomplish, but I think you are missing out on the accepts_nested_attributes_for (docs, tutorial with controller code).

Furthermore I can only recommend you the use simple_forms or formtastic as those gems do a good job when it comes to complex forms and help you a lot with the basic use cases.

Upvotes: 2

Related Questions