Nested Routes, Creating a Vacancy that belongs to a Project
my first question on here. Im quite stuck, 开发者_高级运维im trying to have a link create a vacancy. But some reason all i can get is nil for Vacancy.project... i've tried params[:project_id].to_i in the create method and that gets me 0, but the project id for this case is 156, and on the view params.inspect gives just that.
I've also tried nothing in my new controller, and loads of different attempts to read the session info. The the position code is just that a vacancies builds a position too, but that shouldn't affect much, would it?
Any ideas?
Vacancy controller
def new
@vacancy = Vacancy.new
@vacancy.position = Position.new
@vacancy.project_id = params[:project_id]
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @vacancy }
end
end
The routes im using
resources :projects do
resources :vacancies
end
the link im using:
<%= link_to "Add Vacancy", new_project_vacancy_path(@project) %>
models project... has_many :vacancies
& Vacancy..... belongs_to :project
To an ultra dry implementation, you could do it like this:
class VacanciesController < ApplicationController
before_filter :load_project, :load_vacancy
def new
end
def edit
end
def create
if @vacancy.update_attributes( params[:vacancy] )
flash[:notice] = 'Vacancy successfully created/updated'
redirect_to project_vacancies_path( @project )
else
render :new
end
end
alias :update :create
protected
def load_vacancy
@vacancy = if params[:id].blank?
@project.vacancies.build
else
@project.vacancies.find(params[:id])
end
end
def load_project
@project = Project.find( params[:project_id] )
end
end
精彩评论