I have an object called Job that belong to another object
called client in a many relationship.
Here’s my job model
class Job < ActiveRecord::Base
belongs_to :client
end
Here’s my Client model
class Client < ActiveRecord::Base
has_many :jobs
end
For a new job, I simply want to assign it during creation to a client.
When I try to create a new job however. All im seeing in my view is the id of the job instead of the name and the internals of the created model are also empty.
When I try to edit the job and save it again im recieving the following error.
Client(#2157214400) expected, got String(#2151988620)
Application Trace | Framework Trace | Full Trace
app/controllers/jobs_controller.rb:61:in `block in update'
app/controllers/jobs_controller.rb:60:in `update'
I guess this could be because my controller is wrong in some way but this is my first app so im not quite sure where to look.
Here’s my controller.
class JobsController < ApplicationController
def index
@job = Job.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @job }
end
end
def show
@job = Job.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @job }
end
end
def new
@job = Job.new(params[:id])
respond_to do |format|
format.html # new.html.erb
format.json { render json: @job }
end
end
def edit
@job = Job.find(params[:id])
end
def create
@job = Job.new(params[:jobs])
respond_to do |format|
if @job.save
format.html { redirect_to @job, notice: 'job was successfully created.' }
format.json { render json: @job, status: :created, location: @job }
else
format.html { render action: "new" }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
def update
@job = Job.find(params[:id])
respond_to do |format|
if @job.update_attributes(params[:job])
format.html { redirect_to @job, notice: 'job was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
def destroy
@job = Job.find(params[:id])
@job.destroy
respond_to do |format|
format.html { redirect_to :jobs }
format.json { head :no_content }
end
end
end
Any pointers or a nod in the right direction would be appreciated.
The problem is because Activerecord expected an instance of Client object , and it has method client= (because belogs_to association)
When you bind AR object from request you should use client_id parameter instead of client
you can read about http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to
if client count is short you can use select with client_id as name
Example http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
so you can do something like that
instead of