Note that there are some explanatory texts on larger screens.

plurals
  1. POControlling the Order of Execution in Rails Create Action
    text
    copied!<p>New to Ruby and programming in general. So far I've had no problems finding answers to any questions I've had, but can't find this one.</p> <p>In my app the Teams controller new and create actions are creating several new records across several associated models. One of those records is failing to create because it appears the lower record <code>@pool_user</code> is being executed before <code>@department</code> and thus <code>@department.id</code> is nil and email cannot be null.</p> <p>To test, I removed the <code>@pool_user</code> line and inserted a specific value into <code>:userid =&gt;</code> under <code>@competence</code> and it executed in the expected order, creating all records as expected.</p> <p>I am using Devise for the User model, which I suspect may be influencing it initializing first, but I can't seem to find a way to get them to execute in the correct order.</p> <h2>teams_controller.rb</h2> <pre><code>def new @team = Team.new @department = Department.new @competence = Competence.new @pool_user = User.new respond_to do |format| format.html # new.html.erb format.json { render json: @team } end end def create @team = Team.new(params[:team]) @department = @team.departments.build(:organization_id =&gt; User.current.organization_id, :team_id =&gt; @team.id) @pool_user = @team.users.build(:email =&gt; @department.id).save(:validate =&gt; false) @competence = @team.competences.build(:team_id =&gt; @team.id, :user_id =&gt; @pool_user.id) respond_to do |format| if @team.save format.html { redirect_to @team, notice: 'Team was successfully created.' } format.json { render json: @team, status: :created, location: @team } else format.html { render action: "new" } format.json { render json: @team.errors, status: :unprocessable_entity } end end end </code></pre> <p>Feel free to correct any other bad practices or general noob moves you see here. I just want to figure out why it isn't building in the correct order. Thanks. </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