Rails 3.1:自动选择从Param传递到相关表单的值

时间:2012-01-21 07:48:57

标签: ruby-on-rails ruby forms

项目habtm任务

tasks/show.html.erb我有link_to "Add This Task To Project", new_project_path(:task => @task)

这会将@task参数传递给new_project_path http://localhost:3000/projects/new?task=24

当以这种方式访问​​<select><option>时,如何确保Project#new form中的默认new_project_path是my @ task.title?

===更新===

我正在使用simple_form gem生成select元素

= simple_form_for @project do |f|

        = f.association :task, :collection => current_user.task.collect { |t| t.title }, :prompt => "Select workout"

1 个答案:

答案 0 :(得分:2)

来自simple_form README:“关联助手只是调用引擎下的输入,因此所有可用的选项:select,:radio和:check_boxes也可用于关联。”

所以我用这个(http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select)作为参考。

在您的控制器中,因为您通过GET请求收到了任务ID:

@task = Task.find(params[:task])

在您看来:

= f.association :task, :collection => current_user.task.collect { |t| t.title }, :prompt => "Select workout", :selected => @task.title

看看是否有效。如果没有,请尝试将最后一个参数括在花括号中以使其成为哈希。让我知道它是怎么回事。