Save options after rendering Ruby on Rails

I have a project owned by the user. In my user view, I have a link to add a new project, with a parameter for the user to whom I want to add the project.

<%= link_to 'Add new project', :controller => "project", :action => "new", :id => @user %> Url: /projects/new?id=62 

Adding a project to the user works. The problem is when validation fails when adding a new project and I am doing the rendering.

 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 to save a parameter for a user after rendering? Or is there a better way to do this? Looking at a lot of similar questions, but can't get it to work.

+4
source share
2 answers

try

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

if it doesn't work for you, then try an alternative way to pass the parameter to the rendering action.

It may also help you -> Rails 3 Render => New with option

+1
source

You should not use params[:id] to assign a value to this form field. Instead, add this to your #new action in the controller:

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

and then just write this in your form:

 <%= f.hidden_field :user_id %> 

Since @project was defined in your #new and #create , and since it already contains an instance of Project with user_id assigned to user_id , this value will be automatically added to this field.

+1
source

All Articles