Note that there are some explanatory texts on larger screens.

plurals
  1. POAssociating (has_one) multiple models in form
    primarykey
    data
    text
    <p>I'm unable to associate the foreign key before saving the data (the field 'user_id' for the Network model is blank when stored in the database). I'm new to RoR so please excuse me if my code is sloppy :-)</p> <p>Models:</p> <pre><code>class Network &lt; ActiveRecord::Base belongs_to :user end </code></pre> <p><br></p> <pre><code>class User &lt; ActiveRecord::Base has_one :network, :foreign_key =&gt; "user_id", :dependent =&gt; :destroy </code></pre> <p>Controller:</p> <pre><code>class UsersController &lt; ApplicationController def new @user = User.new @network = @user.build_network @title = "Sign Up" end def create @user = User.new(params[:user]) if (@user.save) @network = Network.new(params[:network]) if (@network.save) sign_in @user flash[:success] = "Welcome!" redirect_to @user else @title = "Sign up" render 'new' end else @title = "Sign up" render 'new' end end </code></pre> <p>I'm able to get all of the user input from the view without issues (using form_for and fields_for). Do I have to explicitly define the has_one association in addition to using @user.build_network ?</p> <p>Per the suggestion of using <code>accepts_nested_attributes_for</code>, I cleaned up my controller to be </p> <pre><code>def new @user = User.new @user.build_network @title = "Sign Up" end def create @user = User.new(params[:user]) if (@user.save) sign_in @user flash[:success] = "Welcome!" redirect_to @user else @title = "Sign up" render 'new' end end </code></pre> <p>The updated association in the User Model:</p> <pre><code>has_one :network, :class_name =&gt; 'Network', :foreign_key =&gt; "user_id", :dependent =&gt; :destroy accepts_nested_attributes_for :network, :reject_if =&gt; :all_blank, :allow_destroy =&gt; true </code></pre> <p>However, the network_attributes are all blank when I submit the form. I have followed the directions in the links provided as well as <a href="http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes" rel="nofollow">http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes</a> (and many more)</p> <p>I don't think it's an issue with the view/form since I'm able to access the attributes using <code>Network.new(params[:network]</code> </p> <p>Any thoughts/suggestions ?</p>
    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.
    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