user3851283
user3851283

Reputation: 347

How to return a selected value from a database collection in Rails?

So I have a database collection labeled @joe, and I am trying to pass the id variable into a link url path. This is in my index.erb.html file.

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

In my articles_controller.rb file, I have

  def index
    @joe = Article.all
  end

I made a loop where it grabs each id number and passes it into the article_url path. I was wondering, in the dropdown box that I created above, when I select a certain value, I want to pass that value into the article.id variable. I'm having trouble with this and it outputs x amount of buttons.

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

I was wondering if it is possible to do this or if I can implement JavaScript or jQuery into this. Any help would be appreciated. Thank you!

And here's the rake routes command results:

      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

Upvotes: 0

Views: 47

Answers (1)

nbermudezs
nbermudezs

Reputation: 2844

Let's try this:

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('/'));
});

Upvotes: 1

Related Questions