0

I have two tables: Client, Inspection

Inspections are created through a form that returns a CollectionProxy related to a given client like so:

inspections_controller.rb

def create    
  @inspcetion = @client.inspections.create(inspection_params)
  redirect_to client_inspections_path(@client) 
end

views/inspections/_form.html

<%= form_for([@client, @client.inspections.build], :html => { :class => 'form' }) do |f| %>

Now I am wondering how to update an existing inspection. I believe that using the same form for my update method, will always create a new object -> .build

Is that right?

The url to the update method seems to call the right inspection ( /clients/cl_id/inspections/insp_id/edit), however the form that is generated appears empty (without any of the information that was included for the creation of the inspection)

<%= link_to 'Edit', edit_client_inspection_path(inspection.client, inspection) %>

I believe that I have to change the form / form_for in the edit view and shouldn't render _form.html.erb, however I am completely stuck on how to accomplish this.

Here is my plain update method from inspections_controller.rb

def update
  @inspection = @client.inspection.find(params[:id])
  respond_to do |format|
    if @inspection.update(inspection_params)
      format.html { redirect_to @inspection, notice: 'Inspection was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render action: 'edit' }
      format.json { render json: @client.inspection.errors, status: :unprocessable_entity }
    end
  end
end

So, how can I update an object that is part of a CollectionProxy? It can't be that hard :)

Hope that my question is concise and that somebody can help me out here.

tereško
  • 58,060
  • 25
  • 98
  • 150
The F
  • 3,647
  • 1
  • 20
  • 28

2 Answers2

1

Instead in your new and edit actions do this

def new
  @client = # query for client
  @inspection = @client.inspections.new
end

def edit
  @client = # query to fetch client
  @inspection = @client.inspection
end

In your partial

<%= form_for([@client, @inspection], :html => { :class => 'form' }) do |f| %>

In this way you can do this using the same partial

Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
  • 1
    Thank you so much, I knew it couldn't be that hard. I'm new to rails and really enjoying this a lot. Thanks again! – The F May 12 '14 at 09:17
1

.build will just create a new ActiveRecord object for that instance. It does the same as .new, except you have to populate the data each time.


From what you've got, I would say the big problem is passing the inspections through per client. To fix this, I would use RSB's answer, and populate the @inspection var in the controller

It's never a good idea to use a .build method in your view, as it's not modular

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147