ruby on rails - Creating a record from a different model view(no new action involved) -


i have has_many & belongs_to associations between company , worker. want able add worker company via link in workers index page. want save worker record belonging logged in company , update company/workers index page new worker added workers.

i have been unable this. here happening:

my routes have like:

  namespace :company     resources :workers, :only => [:index, :create]   end    resources :workers 

i have before_action method has cookie session company access token in controllers:

applicationcontroller:

@company = company.find_by_access_token("vzani6k6") cookies[:access_token] = @company.access_token 

and company::workerscontroller

render :file => "public/401.html", :layout => nil, :status => :unauthorized , return if cookies[:access_token] != @company.access_token 

in workers/index.html.haml path have:

= "there #{@workers.count} workers!"  are: - @workers.each |worker|   = worker.name   = link_to "hire worker", company_workers_path(:worker_id => worker), :method => :post %%br  %p= @company.name 

i want able click "hire worker link" , redirected company/workers.html.haml path list workers updated recent addition of worker added via link.

when click link(say worker #2 in database) instead of taking me company/workers path takes me

company/workers?worker_id=2 

and doesn't save worker association company.

my company/workers controller has following:

  def create     @worker = @company.worker.build(:worker_id => params[:worker_id])     @worker.save     redirect_to :action => 'index'   end 

remember have before_action on controllers saves @company instance variable before calling other controller methods well.

i have model worker belongs_to company & model company has_many workers , have added reference key in migration already.

what problem? why weird route , why records not saving, bit of newb forgive simple question.

at first look, see may have 2 errors:

  1. your company model class has_many workers, assign (or add) worker company believe must like:

    @worker = worker.find(params[:worker_id]) @worker.company = @company @worker.save! # depending in schema, well: # @company.workers << @worker 
  2. to redirect company/workers, use nested routes, must like

    redirect_to company_workers_path(@company) 

hope helps!


Comments