Reputation: 21208
I have a form for creating a ticket, which needs an id of a project. This works but not when it comes to validation. If validation won't pass 'render :new' is executed and the project_id doesn't come with it.
I have tried 'redirect_to new_ticket_path(:project_id => params[:ticket][:project_id]) which renders the form again, but the error messages won't show up so it seems that I need to use 'render :new'.
How can I pass the project_id back to the form or reach project_id from the form without passing it?
def new
@ticket = Ticket.new
@id = params[:project_id]
@project = Project.find(@id)
end
def create
@ticket = Ticket.new(params[:ticket].merge(:user_id => current_user.id))
if @ticket.save
redirect_to @ticket
else
render :new <--- will render without the project_id
end
end
Upvotes: 0
Views: 200
Reputation: 456
Write project id into a hidden field in your form and you will okay. And don't forget to initialize @id
in your create action
def new
@ticket = Ticket.new
@id = params[:project_id]
@project = Project.find(@id)
end
def create
@ticket = Ticket.new(params[:ticket].merge(:user_id => current_user.id))
@id = params[:project_id] # but make sure it is under this key in params
if @ticket.save
redirect_to @ticket
else
render :new <--- will render without the project_id
end
end
and in the form add
<%= hidden_field :project_id, '', value: @id %>
Upvotes: 0
Reputation: 475
That will render just the view for 'new', but will not run the controller action. You'd need to set up your variables for the 'new' view in your 'create' action.
From http://guides.rubyonrails.org/layouts_and_rendering.html#using-render
Using render with :action is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does not run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling render.
The easiest way around this is to change 'new':
def new
@ticket = Ticket.new(:project_id => params[:project_id])
end
and change any references to @project in your 'new' form to @ticket.project. At that point, you shouldn't have to add anything to your 'create' action as long as your form includes a hidden field for the ticket's project id.
Upvotes: 1
Reputation: 14402
The easiest way to get this working (and I would do this anyway) is to nest the task resource under projects. That way you will always have project_id available in params.
# config/routes.rb
resources :projects do
resources :tasks
end
The urls will look like projects/123/tasks/new
etc. Take a look at rake routes
.
Upvotes: 1
Reputation: 417
Why don't you use:
flash[:alert] = @ticket.errors.inspect
redirect_to new_ticket_path(:project_id => params[:ticket][:project_id])
Upvotes: -1