Note that there are some explanatory texts on larger screens.

plurals
  1. POUse rails nested model to *create* outer object and simultaneously *edit* existing nested object?
    primarykey
    data
    text
    <p>Using Rails 2.3.8</p> <p>Goal is to <strong>create</strong> a Blogger while simultaneously <strong>updating</strong> the nested User model (in case info has changed, etc.), OR create a brand new user if it doesn't exist yet.</p> <p>Model:</p> <pre><code>class Blogger &lt; ActiveRecord::Base belongs_to :user accepts_nested_attributes_for :user end </code></pre> <p>Blogger controller:</p> <pre><code>def new @blogger = Blogger.new if user = self.get_user_from_session @blogger.user = user else @blogger.build_user end # get_user_from_session returns existing user # saved in session (if there is one) end def create @blogger = Blogger.new(params[:blogger]) # ... end </code></pre> <p>Form:</p> <pre><code>&lt;% form_for(@blogger) do |blogger_form| %&gt; &lt;% blogger_form.fields_for :user do |user_form| %&gt; &lt;%= user_form.label :first_name %&gt; &lt;%= user_form.text_field :first_name %&gt; # ... other fields for user &lt;% end %&gt; # ... other fields for blogger &lt;% end %&gt; </code></pre> <p>Works fine when I'm <strong>creating</strong> a new user via the nested model, but fails if the nested user already exists and has and ID (in which case I'd like it to simply update that user).</p> <p>Error:</p> <pre><code>Couldn't find User with ID=7 for Blogger with ID= </code></pre> <p>This SO question deals with a similar issue, and only answer suggests that Rails simply won't work that way. The answer suggests simply passing the ID of the existing item rather than showing the form for it -- which works fine, except I'd like to allow edits to the User attributes if there are any.</p> <p><a href="https://stackoverflow.com/questions/3783247/deeply-nested-rails-forms-using-belong-to-not-working">Deeply nested Rails forms using belong_to not working?</a></p> <p>Suggestions? This doesn't seem like a particularly uncommon situation, and seems there must be a solution.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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