Keep params after render Ruby on Rails

天大地大妈咪最大 提交于 2019-12-01 16:53:27

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/14975486/keep-params-after-render-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!