Reputation: 71
I want to update a column worker inside job table with the user id of from the bids table
Here is my controller
def worker
@bid = Bid.find(params[:id])
@job = Job.find(params[:id])
@job.update_attributes(worker: @bid.user.id)
redirect_to projects_path
end
end
and i Created a put "worker" in the routes
and here's the link that i'm trying to use
<%= link_to 'Assign To Project', worker_path(bid), method: :put%>
The Bid and Job are bod in each loop The Logic is working in rails console but i think the error is how to get the job id and bid id , it works once but only updating the first job
Upvotes: 0
Views: 68
Reputation: 71
Finally it's working , sorry for the confusing this is the first time i ask a question here ,
The controller
def worker
@job = Job.find params[:job_id]
@bid = Bid.find params[:bid_id]
if @job.worker.nil?
redirect_to projects_path if @job.update_attributes worker: @bid.user.id
else
redirect_to projects_path , notice: "#{@bid.user.name} assigned on this project"
end
end
The Link
<%= button_to 'Assign To Project',
job_worker_path(job, bid),
method: :put,
params: { bid_id: bid.id }%>
The Route
resources :jobs do
match 'worker', to: 'jobs#worker', via:[:put]
resources :bids
end
I was trying to assign bid.user.id to job.worker
Upvotes: 0
Reputation: 76774
#config/routes.rb
resources :jobs do
put ":bid_id/worker", action: :worker #-> url.com/jobs/:job_id/:bid_id/worker
end
#app/controllers/jobs_controller.rb
class JobsController < ApplicationController
def worker
@job = Job.find params[:job_id]
@bid = Bid.find params[:bid_id]
redirect_to projects_path if @bid.update worker: @job.user
end
end
The above will you give you the ability to call the following:
<%= link_to "Update Worker", jobs_worker_path(job, bid), method: :put %>
What you're doing should really be handled by your ActiveRecord Associations
.
For example, I am expecting you to have a foreign_key
of worker_id
in your jobs
table; hence if you call update_attributes worker: @job.user.id
, it's an antipattern.
The above code should work for you, however it's still hacky.
Upvotes: 0
Reputation: 102036
Use button_to
instead of link_to
if you want to pass several parameters.
Generates a form containing a single button that submits to the URL created by the set of options.
<%= button_to 'Assign To Project',
worker_path(bid),
method: :put,
params: { bid_id: some_variable }
%>
Upvotes: 2