Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep params after render Ruby on Rails

I have a Project that belongs to User. In my user view I have a link to add a new project, with the parameter for the user I want to add the project to.

<%= link_to 'Add new project', :controller => "project", :action => "new", :id => @user %>

Url: /projects/new?id=62 

Adding a project to a user works. The problem is when the validation fails while adding a new project and I do a render.

def create

    @project = Project.new(params[:project])

    if @project.save
        redirect_to :action => "show", :id => @project.id
    else
        render :action => "new"
    end

end

view:

<%= form_for @project do |f| %>

    <%= f.label :name %>
    <%= f.text_field :name %>

    <%= f.hidden_field :user_id , :value => params[:id] %>

    <%= f.submit "Create project" %>
<% end %>

routes

resources :users do
 resources :projects
end

How can I keep the parameter for the user after the render? Or is there some better way to do this? Been looking at a lot of similar questions but can't get it to work.

like image 676
ana Avatar asked Feb 20 '13 08:02

ana


2 Answers

try

render :action => "new", :id => @project.id

if its not works for you, then try alternate way to pass the parameter to your render action.

This can also help you-> Rails 3 Render => New with Parameter

like image 137
Gopal S Rathore Avatar answered Nov 14 '22 00:11

Gopal S Rathore


You shouldn't use params[:id] to assign value to this form field. Instead, add this to your #new action in controller:

def new
  @project = Project.new(user_id: params[:id])
end

and then just write this in your form:

<%= f.hidden_field :user_id %>

Because @project was defined in your #new and #create actions and because it already contains a Project instance with a user_id assigned to it, the value would automatically be added to this field.

like image 26
snitko Avatar answered Nov 14 '22 01:11

snitko