选择从表中填充的框

时间:2012-12-07 16:10:14

标签: ruby-on-rails ruby-on-rails-3 drop-down-menu html-table auto-populate

我目前有一个表由多个选择框和两个单选按钮排序/过滤,它工作正常。我会从表中自动填充选择框。具体来说,我想要一个状态选择框,从我的文章表中的状态填充。我目前有一个articles.rb模型和state.rb模型,我已经建立了关系。 article belongs_to:state,state has_many:article。到目前为止,这是我的代码:

index.html.erb

<%= form_tag articles_path, :method => "GET" do %>

  <%= radio_button_tag :gender_search, "M" %>
  <%= label_tag :gender_search_M, "M" %>
  <%= radio_button_tag :gender_search, "F" %>
  <%= label_tag :gender_search_F, "F" %>

  <%= select_tag :state_search, options_for_select([['Select a state', 0],['-----------', 0],['LA', 'LA'],['MS', 'MS'], ['TX', 'TX']], @prev_state) %>
  <%= select_tag :city_search, options_for_select([['Select a city', 0],['----------', 0],['Mandeville', 'Mandeville'],['Covington', 'Covington']], @prev_city) %>

  <%= submit_tag "Go" %>

<% end %>
<table class="table table-striped table-bordered span8 table-condensed" id="articles_table">
  <thead class="header">
    <tr>
      <th>ID</th>
      <th>Title</th>
      <th>Description</th>
      <th>Created_At</th>
    </tr>
  </thead>
  <tbody>
    <%= render @articles %>
  </tbody>
</table>

_article.html.erb

<tr>
  <td> <%= article_counter +1 %> </td>
  <td> <%= article.Title %> </td>
  <td> <%= article.Description %> </td>
  <td> <%= article.Created_At %> </td>
</tr>

article.rb

class Article < ActiveRecord::Base
  belongs_to :state


def self.city_search(city_search)
    if city_search
      where('City LIKE ?', "%#{city_search}%")
    else
      scoped
    end
end
def self.state_search(state_search)
    if state_search
      where('State LIKE ?', "%#{state_search}%")
    else
      scoped
    end
end

如果我需要发布更多代码或更多信息,请与我们联系。任何可以帮助我的事情都会很棒。

2 个答案:

答案 0 :(得分:2)

值得一看

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

我认为对于州,你可以做类似

的事情
<%= collection_select :state_id, State.all, :id, :name, multiple: true, :prompt => "Please Select" %>

现在这可能不太准确,但它是如何我在我的应用程序中做它并且它有效(虽然国家而不是国家)

答案 1 :(得分:0)

查看本网站后: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

我发现我实际上并不需要为State和City设置模型。我需要做的就是创建一个从我的文章表中选择不同状态的collection_select。这是它的样子:

<%= collection_select :article, :state, Article.select(:state).uniq.order('state ASC'), :state, :state, {:prompt => 'Select a State'},{:name => "state_search"} %> 

所以我所要做的就是设置像网站所说的collection_select并添加 Article.select(:state).uniq.order('state ASC')作为我的集合来选择uniq来自我的文章表。