Rails 3.2 - Nested Resource Passing ID

2019-09-08 16:11发布

问题:

Okay so my associations are:

Outlet -> has_many :monitorings
Monitoring -> belongs_to :outlet

My Routes:

resources :outlets do
   resources :monitorings
end

View:

<%= link_to new_outlet_monitoring_path(@outlet) %>

When I click the link, the logs show that the outlet_id is passed as a parameter to the new page correctly. But when saving the monitoring record, the outlet_id becomes nil.

Any help?

UPDATE:

# views/monitorings/_form.html.erb  

<%= form_for(@monitoring) do |f| %>
<h2>Type of Monitoring</h2>
<fieldset data-role="controlgroup" >
    <div class="radio-group">
      <%= f.radio_button :mtype, "Full" %><%= f.label :mtype, "Full", value: "Full" %>
      <%= f.radio_button :mtype, "Partial" %><%= f.label :mtype, "Partial", value: "Partial" %>
      <%= f.radio_button :mtype, "None" %><%= f.label :mtype, "None", value: "None" %>
    </div>
</fieldset>
<hr>
<%= f.submit "Next Step" %>
<% end %>

And the controller:

# controllers/monitoring_controller.rb  


def new
    @monitoring = Monitoring.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @monitoring }
    end
end

def create
  @monitoring = Monitoring.new(params[:monitoring])

  respond_to do |format|
    if @monitoring.save
      format.html { redirect_to @monitoring, notice: 'Monitoring was successfully created.' }
      format.json { render json: @monitoring, status: :created, location: @monitoring }
    else
      format.html { render action: "new" }
      format.json { render json: @monitoring.errors, status: :unprocessable_entity }
    end
  end
end

回答1:

This is most likely an issue with the way you are creating the new monitoring record. Can we see your form and your create controller action?