【发布时间】:2017-03-13 00:23:05
【问题描述】:
在项目展示页面上,我在“创建新任务”中传递了一个非常简单的参数,该参数存储了它来自哪个项目:
@project.id), :class=> "btn btn-info col-md-12" %>所以当我为它创建一个新任务时,它将它存储在我的新任务表单的 URL 中,如下所示:
http://localhost:3000/task/new?project_id=5
我的新表格如下:
<div class="container sign-in-register">
<div class="authform">
<%= form_for @task, :html => {:multipart => true} do |f| %>
<h3>Add a task for this project...</h3><br/>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= hidden_field_tag 'project_id', @project_id %>
<%= f.fields_for :taskrelationships do |ff| %>
<%= ff.hidden_field :taskproject_id, value: @project_id %>
<%= ff.label :task_url %>
<%= ff.text_field :task_url, class: 'form-control' %>
<% end %>
<br clear="all">
<%= f.submit "Save Task", class: "btn btn btn-info" %>
<% end %>
</div>
</div>
如您所见,我在表单中使用了嵌套属性(我正在创建一个任务和一个 TaskRelationship。现在,当我尝试在不填写所有必填字段的情况下保存时,会引发验证,但由于某种原因它将我重定向到:
http://localhost:3000/tasks
代替原来的:
http://localhost:3000/tasks/new?project_id=5
我已经阅读了很多帖子,但似乎没有一个回答这个特殊情况。下面的 stackO 帖子已关闭,但是当我使用任务而不是用户尝试它时,它仍然找不到 task_ID
我怎样才能让 rails 简单地呈现与我开始时完全相同的 url - 看起来这应该很容易,所以必须遗漏一些小东西。
我的控制器操作:
def new
@project_id = params[:project_id]
@task = Task.new
@task.taskrelationships.build
end
def create
@project = Project.find(params[:project_id])
@task = Task.new(task_params)
if @task.save
flash[:success] = "This task has been added."
@task.taskrelationships.create!(@taskrelationships_params)
redirect_to tasks_project_path(@project)
else
@task.taskrelationships.build(@taskrelationships_params)
flash[:alert] = @task.errors.full_messages.to_sentence
render :new
end
end
private
def task_params
@taskrelationships_params = params.require(:task).permit(taskrelationships_attributes: [
:task_url,
:taskproject_id
])[:taskrelationships_attributes]["0"]
params[:task].delete(:taskrelationships_attributes)
params.require(:task).permit(
:name,
:user_id,
taskrelationships_attributes: [
:task_url,
:taskproject_id
]
).merge(owner: current_user)
end
使用路线更新
resources :projects do
resources :reviews, except: [:destroy]
member do
get :tasks
end
end
resources :tasks
resources :taskrelationships, only: [:create, :destroy] do
post :vote, on: :member, controller: "task_relationships"
end
感谢您的帮助...
【问题讨论】:
-
我对你的问题有点困惑 - 它与创建新任务有关,我假设控制器代码适用于你的 TasksController 在这种情况下,为什么你的网址是
project/new?task_id=5- 这个怎么样任务有id吗?您不希望这会在 ProjectsController 中进行新的操作吗? -
道歉 - 表格应该是localhost:3000/tasks/new?project_id=5(我最初写错了,但现在已经更新了)
-
(所以我正在查看项目配置文件,并且有一个按钮可以创建新任务...打开 localhost:3000/tasks/new?project_id=5)。任务还没有 id,项目会有。
-
是的,完全理解 - 感谢您的快速更正和解释 :) 好的,只有一点......您需要在调用
render :new之前设置@project_id(虽然我不认为那是重定向问题的原因 - 值得设置它,但只是为了确保)。其次,您能否发布与任务相关的路线。 -
确定 - 刚刚发布了我的路线。
标签: ruby-on-rails forms validation ruby-on-rails-4 parameter-passing