Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to interact with a join table, with a form's create action?
    primarykey
    data
    text
    <p>*Note to view all code, follow the link</p> <p>I am creating new "accounts". Each new Account have_many :users. <strong>Users have_and_belong_to_many roles</strong>. I am trying to assign EXISTING roles to new users, in the new account form. Typically an easy process however... </p> <p>The have_and_belong_to_many association between Users and Roles implies that users and roles are associated by a join table. I don't have a model to work with. So I am not sure how to go about coding this. I'm able to create new Roles, using methods outlined <a href="https://stackoverflow.com/questions/2258797/complex-forms-managing-multiple-models-in-a-single-form-3rd-degree-madness">here</a> (in the answer) but I am clueless as to assign existing Roles to new users through the account model.</p> <p>The SQl equivalent would be something like this: <code>SQL (0.1ms) INSERT INTO "roles_users" ("role_id", "user_id") VALUES (6, 29)</code>Where I need 29 to function like the ID of the new user created in rails i.e. VAULES (6, ID)</p> <p>Current Code: (creates a new role)</p> <pre><code>&lt;% f.fields_for :users do |builder| %&gt; &lt;%= render 'user_fields', :f =&gt; builder %&gt; &lt;p&gt;Login : &lt;%= f.text_field :login %&gt; &lt;p&gt;Email : &lt;%= f.text_field :email %&gt; &lt;p&gt;Password : &lt;%= f.password_field :password %&gt; &lt;p&gt;Confirm Password : &lt;%= f.password_field :password_confirmation %&gt; &lt;%= f.hidden_field :account_id, :value =&gt; :id %&gt; &lt;% f.fields_for :roles do |builder| %&gt; &lt;%= builder.hidden_field :name, :value =&gt; 'test' %&gt; &lt;% end %&gt; </code></pre> <p>Account.rb</p> <pre><code>has_many :users accepts_nested_attributes_for :users </code></pre> <p>User.rb</p> <pre><code>has_and_belongs_to_many :roles accepts_nested_attributes_for :roles </code></pre> <p>accounts_controller.rb</p> <pre><code>def new @account = Account.new #builds user and roles in memory 1.times do user = @account.users.build 1.times { user.roles.build } end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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