我有一个表呼叫市政和另一个电话表格。表单有1个市,并存储一个名为municipality_id的变量。
当您从下拉菜单中选择一个状态时,它只会显示具有该state_id的Municipalities。此时,我还想显示与市政当局相关的所有表格。
我只是难以获得该市的表格,而不是全部。
到目前为止,这是我的代码:
查看:
<div class="form-group">
<div>
<% @municipalities.each do |municipality| %>
<tr class="active">
<td><%= link_to municipality.name, municipality_path(municipality) %></td>
<td><%= municipality.state.state %></td>
<td><%= municipality.population %></td>
<% if user_signed_in? %>
<td><%= link_to 'Show', municipality %></td>
<td><%= link_to 'Edit', edit_municipality_path(municipality) %></td>
<td><%= link_to 'Destroy', municipality, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
<% @forms.each do |form| %>
<tr>
<%# if @forms.municipality_id == municipality %>
<% @forms.each do |form| %>
<td><%= form.form_name %></td>
<% end %>
<%# end %>
<% end %>
<tr>
<% end %>
</div>
控制器:
def index
@states = State.all
if params[:state_id].present?
@state = params[:state_id]
@municipalities = Municipality.where(state_id: @state)
@forms = Form.where(municipality_id: @municipalities)
else
@states = State.all
@municipalities = Municipality.all
end
端
架构:
create_table "forms", force: :cascade do |t|
t.string "form_name"
t.string "form_link"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "municipality_id"
t.integer "department_id"
end
add_index "forms", ["department_id"], name: "index_forms_on_department_id"
add_index "forms", ["municipality_id"], name: "index_forms_on_municipality_id"
create_table "municipalities", force: :cascade do |t|
t.string "name"
t.integer "form_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "population"
t.integer "state_id"
end
在从下拉列表中选择状态后,如何仅显示与市政当局关联的表格的任何帮助。谢谢!
修正了视图,感谢下面的回复
<%if @state != nil %>
<% @state.municipalities.each do |municipality| %>
<tr class="active">
<td><%= link_to municipality.name, municipality_path(municipality) %></td>
<td><%= municipality.state.state %></td>
<td><%= municipality.population %></td>
</tr>
<% municipality.forms.each do |form| %>
<tr>
<td><%= form.form_name %></td>
</tr>
<% end %>
<% end %>
<% end %>
答案 0 :(得分:1)
您希望市政当局拥有多种形式,以及属于单一市政当局的表格。因此,您不应该在市政府表中定义form_id。没有一个,但与市政当局有关的多种形式。
在您的模型中定义关系如下:
<强> state.rb 强>
has_many :municipalities
<强> municipality.rb 强>
belongs_to :state
has_many :forms
<强> form.rb 强>
belongs_to :municipality
然后在您的控制器中加载@state = State.find(params[:state_id]
的状态。然后,您可以使用@state.municipalities.each do |municipality|
遍历表单中的所有城市,并在该区块内执行municipality.forms.each do |form|