javascript - 从 Rails 的集合中返回选定的值并将其发送到 URL

标签 javascript jquery ruby-on-rails ruby ruby-on-rails-3

所以我有一个标记为 @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(**parameter for article.id**), :method => 'get' %>
<% end %>

我正在尝试访问此 articles_url 链接(即 localhost:3000/articles/1、localhost:3000/articles/2),其中数字代表 id 来自集合 @joe 元素的值。 我想知道是否可以做到这一点,或者我是否可以在其中实现 JavaScript 或 jQuery。任何帮助,将不胜感激。谢谢!

这是 rake 路由命令结果:

      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

最佳答案

<% @joe.each do |article| %>
    <%= button_to "SELECT", article_url(article) %>
<% end %>

Rails 将调用文章上的 id,并且article_url 将在此上下文中获取

为什么调用索引参数@joe?

您是否考虑过将其称为@articles?

关于javascript - 从 Rails 的集合中返回选定的值并将其发送到 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33282724/

相关文章:

ruby-on-rails - Heroku pg迁移错误 "PG:DataCorrupted: Error"

javascript - 通过 jqXhr 访问 Ajax 调用响应 PHP

jquery - 如何使用 jQuery 多次更改图像的 alt 属性?

php - 在不刷新页面的情况下如何使用ajax/jQuery显示数据库中的值

javascript - 可以使用javascript打开和写入本地文件吗?

ruby-on-rails - 在 Ruby 中获取两个日期之间的日期对象数组的最有效方法是什么?

ruby-on-rails - 如何在 rails 中用 %20 替换空间

javascript - 如何在 node-sql 中设置 SQL 方言?

javascript - 使用媒体查询后是否可以更改 html?

javascript - Safari 后退按钮在使用时不会重新加载页面