8

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.

ana
  • 475
  • 4
  • 10
  • 21

2 Answers2

4

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

Community
  • 1
  • 1
Gopal S Rathore
  • 9,885
  • 3
  • 30
  • 38
4

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.

orion3
  • 9,797
  • 14
  • 67
  • 93
  • this is the rails way guys follow this, assigned the value manually using params[:id] will give u more trouble since the `render :new` for failed forms not returning the params automatically thus why the question is asked at first – buncis Jan 02 '22 at 06:58