Reputation: 159
I have the following:
Clients have many Reports and Reports belong to a client.
However on the creation of the Report it is not assigning the client_id into the database, but not sure why?
Am i doing something wrong here?
Client Model
class Client < ActiveRecord::Base
has_many :reports, :dependent => :destroy
end
Report Model
class Report < ActiveRecord::Base
has_attached_file :report
belongs_to :client
end
Client Controller (Update)
# PUT /clients/1
# PUT /clients/1.json
def update
@client = Client.find(params[:id])
respond_to do |format|
if @client.update_attributes(params[:client])
format.html { redirect_to [:admin,@client], :notice => 'Client was successfully updated.' }
format.json { head :ok }
else
format.html { render :action => "edit" }
format.json { render :json => @client.errors, :status => :unprocessable_entity }
end
end
end
Report Controller (Create)
# POST /reports
# POST /reports.json
def create
@report = Report.new(params[:report])
@report.client_id = params[:client][:client_id]
respond_to do |format|
if @report.save
format.html { redirect_to '/admin/clients', :notice => 'Report was successfully created.' }
format.json { render :json => @report, :status => :created, :location => @report }
else
format.html { render :action => "new" }
format.json { render :json => @report.errors, :status => :unprocessable_entity }
end
end
end
Client Edit View
<%= form_for([:admin, @client.reports.build]) do |f| %>
<label class="formlabel">Report Upload</label>
<%= f.file_field :report, :class=>"text-input small-input" %>
<div class="actions">
<br />
<%= f.submit 'Upload', :class => 'button' %>
</div>
<% end %>
Assistance would be appreciated!
Upvotes: 0
Views: 128
Reputation: 159
Stupid Mistake it seems needed to up the end function on the form-for for the client to close it off before opening the form-for the reports.
Then add the field for the client_id and now just hide the field as per Adam suggestion.
Thanks Steph for suggestions as this help me solve this mistake.
Thanks Everyone! :-)
Upvotes: 0
Reputation: 2136
I'm curious; because you're using .build
in the form_for, the client may already be in the url.
What if you remove:
@report.client_id = params[:client][:client_id]
and submit, what happens then? Because this line is looking incorrectly at the params, so I wonder if you are overwriting that you built in the form_for
Either that, or a hidden field like @Adam said would work.
Upvotes: 1
Reputation: 3158
The client_id doesn't have a related input field in the form on your view. You could add something to your form like:
f.hidden_field :client_id
And then in your controller, set it as:
@report.client_id = params[:report][:client_id]
Alternatively, you could include the client_id in the url.
Upvotes: 1