0

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

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>

文章.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

如果我需要发布更多代码或更多信息,请告诉我。任何可以帮助我的东西都会很棒。

4

2 回答 2

2

值得一看

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

我认为对于州你可以做类似的事情

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

现在这可能不准确,但它是我在我的应用程序中的操作方式和它的工作原理(尽管是国家而不是州)

于 2012-12-07T16:28:53.027 回答
0

看了这个网站后: http: //apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

我发现我实际上不需要为州和市设置模型。我需要做的就是创建一个 collection_select,从我的 Articles 表中选择 Distinct States。这是它的样子:

<%= 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')作为我的集合,以便从我的Articles 表中选择uniq 状态。

于 2012-12-17T15:40:33.550 回答