0

我有一张用于创建票据的表单,该表单需要一个项目的ID。这有效,但不涉及验证。如果验证不会通过'render:new'并且project_id不附带它。发送参数进行渲染

我已经尝试了'redirect_to new_ticket_path(:project_id => params [:ticket] [:project_id]),它再次呈现窗体,但错误消息不会显示出来,所以看起来我需要使用'render :新'。

如何将project_id传递回表单或从表单到达project_id而不传递它?

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 

回答

1

这会使刚刚查看'新',但不会运行控制器操作。您需要在“创建”操作中为“新”视图设置变量。

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.

解决这个问题的最简单的方法是改变 '新':

def new 
    @ticket = Ticket.new(:project_id => params[:project_id]) 
end 

,并更改任何引用你的 '新' 的形式向@project @ ticket.project 。此时,只要您的表单包含工单的项目ID的隐藏字段,就不必为“创建”操作添加任何内容。

+0

尝试了您的解决方案,但得到以下错误:“未定义的方法项目”为#“...引用 - >”<%= f.hidden_​​field:project_id,:value => @ ticket.project.id %>“ – holyredbeard 2013-02-14 15:12:58

+0

好吧,像Ticket,Project和project_id这样的名字,我认为这就是名字。您的票务必须有'belongs_to:项目'或类似的,对吗?您需要使用关系的名称。 – Jim 2013-02-14 15:14:52

+0

.....有一个? :) – holyredbeard 2013-02-14 15:15:20

0

将项目编号写入表单中的隐藏字段,你会好的。而且不要忘了在创建操作以初始化@id

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 

,并在表单中添加

<%= hidden_field :project_id, '', value: @id %> 
+0

我已经有了project_id的隐藏字段,但是当我在错误后渲染表单时,我再也没有它了。 – holyredbeard 2013-02-14 15:01:01

+0

假设你在表单中使用你的'@ id'变量,对吧?您必须在您的创建操作中初始化它'@id = params [:project_id]'(或者它在params散列中的任何位置) – Phobos98 2013-02-14 15:03:30

+0

是的,我已经这样做了。问题是,当我错误后再次渲染:new时,project_id将不会跟随。 – holyredbeard 2013-02-14 15:19:45

-1

你为什么不使用:

flash[:alert] = @ticket.errors.inspect 
redirect_to new_ticket_path(:project_id => params[:ticket][:project_id]) 
+0

这显示我在闪光消息中的错误,这不是我想要的。 – holyredbeard 2013-02-14 15:04:33

1

最简单的方法是使任务资源嵌入到项目中。这样,你将永远有params中的project_id。

# config/routes.rb 
resources :projects do 
    resources :tasks 
end 

的URL看起来像projects/123/tasks/new等等看看rake routes