Rails - 使用下拉列表中的信息为方法操作提供参数

时间:2012-07-03 10:32:08

标签: ruby-on-rails session drop-down-menu arguments

目前,我在项目/索引视图中有一个项目列表。点击'显示'在项目旁边,它转到该项目的show视图。在那里,您可以点击“选择项目”,然后将该项目的ID传递到会话中,这样只有与该项目相关的相关任务才会显示在其他页面中。

我想要做的是为项目提供一个下拉菜单(这样您就不会看到所有项目的大量长桌),并在下拉菜单旁边有两个按钮 - 一个用于查看更多信息(即转到该项目的展示视图),另一个用于选择项目'。我怎样才能使它们具有正确的信息(即项目ID),以便它们正常运行?谢谢!

以下是所有相关代码:

项目下拉列表:

<%= collection_select(:project, :id, Project.all, :id, :name) %>

链接到show view:

<%= link_to 'Show', project, :class =>"btn btn-primary btn-mini" %>

链接到&#39;选择项目&#39;

<%= link_to 'Select Project', select_project_project_path(@project), :method => :post, :class => 'btn btn-primary btn-small' %>

在项目控制器中选择项目操作:

def select_project
  project = Project.find(params[:id])
  session[:project_id] = project.id
  redirect_to root_url, notice: "Current project set to: #{project.name}, ID: #{project.id}"
end

更新:

以下是相关路线:

resources :projects do
  member do
    post :select_project
  end
end

rake routes | grep项目的结果:

 select_project_project POST   /projects/:id/select_project(.:format)  projects#select_proj
               projects GET    /projects(.:format)                     projects#index
                        POST   /projects(.:format)                     projects#create
            new_project GET    /projects/new(.:format)                 projects#new
           edit_project GET    /projects/:id/edit(.:format)            projects#edit
                project GET    /projects/:id(.:format)                 projects#show
                        PUT    /projects/:id(.:format)                 projects#update
                        DELETE /projects/:id(.:format)                 projects#destroy

2 个答案:

答案 0 :(得分:0)

那怎么样?

<%= collection_select :project, :id, Project.all, :id, :name %>
<%= link_to "Show", @project, id: "show_project_btn" %>
<%= link_to "Select" select_project_project_path(@project), id: "select_project_btn" %>

<script type="javascript">
  $('#project_id').change(function(){
    var project_id = $(this).val();
    $('#show_project_button').attr('href', '/project/' + project_id);
    $('#select_project_button').attr('href', '/projects/' + project_id + '/select_project');
  })
</script>

答案 1 :(得分:0)

您可以创建和使用&#34; show&#34;和&#34;选择项目&#34;不基于项目ID的路由(并且不要与Rails资源路由冲突),并继续将项目ID作为params对象的一部分发送到控制器的操作中。

在routes.rb中,

get 'show_project', to: 'projects#show'
get 'select_project', to: 'projects#select_project'

在您的视图中,使用show_project_pathselect_project_path等路径名来提交请求。