Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to set up your models and relationships like so:</p> <pre><code>class Message &lt; ActiveRecord::Base has_many :message_groups has_many :groups, :through =&gt; :message_groups accepts_nested_attributes_for :message_groups #Note this here! end class Group &lt; ActiveRecord::Base has_many :message_groups has_many :messages, :through =&gt; :message_groups end class MessageGroup &lt; ActiveRecord::Base belongs_to :group belongs_to :message end </code></pre> <p>Then in your form...</p> <pre><code>&lt;% form_for(@message) do |f| %&gt; &lt;%= f.error_messages %&gt; &lt;% f.fields_for :message_groups do |g| %&gt; &lt;p&gt; &lt;%= g.label :group_id, "Group" %&gt; &lt;%= g.select :group_id, Group.find(:all).collect {|g| [ g.title, g.id ] } %&gt; &lt;/p&gt; &lt;% end %&gt; &lt;p&gt; &lt;%= f.submit 'Update' %&gt; &lt;/p&gt; &lt;% end %&gt; </code></pre> <p>And here's my migrations for completeness</p> <pre><code>class CreateGroups &lt; ActiveRecord::Migration def self.up create_table :groups do |t| t.string :title t.timestamps end end def self.down drop_table :groups end end class CreateMessages &lt; ActiveRecord::Migration def self.up create_table :messages do |t| t.text :body t.timestamps end end def self.down drop_table :messages end end class CreateMessageGroups &lt; ActiveRecord::Migration def self.up create_table :message_groups do |t| t.integer :message_id t.integer :group_id t.timestamps end end def self.down drop_table :message_groups end end </code></pre> <p>Hope this helps...!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload