ruby on rails - Adding rows that are only associate with previous row -
i have table call municipalities , call forms. forms have 1 municipality, , stores variable called municipality_id.
when select state drop down menu, show municipalities state_id. @ point, want display forms associated municipality.
i'm having trouble getting municipality's forms show, , not of them.
here code far:
view:
<div class="form-group"> <div> <% @municipalities.each |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 sure?' } %></td> <% end %> <% @forms.each |form| %> <tr> <%# if @forms.municipality_id == municipality %> <% @forms.each |form| %> <td><%= form.form_name %></td> <% end %> <%# end %> <% end %> <tr> <% end %> </div>
controller:
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
end
schema:
create_table "forms", force: :cascade |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 |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
any on how display forms associated municipality, after select state drop down. thanks!
fixed view, response below
<%if @state != nil %> <% @state.municipalities.each |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 |form| %> <tr> <td><%= form.form_name %></td> </tr> <% end %> <% end %> <% end %>
you want municipality have many forms, , form belong single municipality. therefore shouldn't define form_id in municipality table. there not one, multiple forms associated municipality.
in models define relations follows:
state.rb
has_many :municipalities
municipality.rb
belongs_to :state has_many :forms
form.rb
belongs_to :municipality
then in controller load state @state = state.find(params[:state_id]
. can iterate on municipalities in form @state.municipalities.each |municipality|
, inside block municipality.forms.each |form|
Comments
Post a Comment