如何从Rails中的数据库集合中返回选定的值?

时间:2015-10-22 01:12:30

标签: javascript jquery ruby-on-rails

所以我有一个标记为@joe的数据库集合,我试图将id变量传递给链接URL路径。这是在我的index.erb.html文件中。

<%= select_tag "article", options_from_collection_for_select(@joe, 'id', 'title'), 
prompt: "Select Something" %>

在我的articles_controller.rb文件中,我有

  def index
    @joe = Article.all
  end

我创建了一个循环,它抓取每个id数字并将其传递到article_url路径。我想知道,在我上面创建的下拉框中,当我选择某个值时,我想将该值传递给article.id变量。我遇到了麻烦,输出了x个按钮。

<% @joe.each do |article| %>
    <%= button_to "SELECT", article_url(article.id), :method => 'get' %>
<% end %>

我想知道是否可以这样做,或者我是否可以在其中实现JavaScript或jQuery。任何帮助,将不胜感激。谢谢!

这是rake routes命令结果:

      Prefix Verb   URI Pattern                  Controller#Action
  home_index GET    /home/index(.:format)        home#index
    articles GET    /articles(.:format)          articles#index
             POST   /articles(.:format)          articles#create
 new_article GET    /articles/new(.:format)      articles#new
edit_article GET    /articles/:id/edit(.:format) articles#edit
     article GET    /articles/:id(.:format)      articles#show
             PATCH  /articles/:id(.:format)      articles#update
             PUT    /articles/:id(.:format)      articles#update
             DELETE /articles/:id(.:format)      articles#destroy
        root GET    /                            home#index

1 个答案:

答案 0 :(得分:1)

让我们试试这个:

ERB

<%= form_tag article_path do %>
  <%= select_tag "id", options_from_collection_for_select(@joe, 'id', 'title'), prompt: "Select Something", class: 'select' %>

  <%= button_tag 'SELECT', class: 'button' %>
<% end %>

JS

$('.button').on('click', function() {
  var path = $('form').attr('action');
  var articleId = $('.select').val();
  $.get([path, articleId].join('/'));
});