Dynamic nested form when changing the selection window

I used the nested model of the Ryan bates model, it works fine, but
I have two i models, e storage and order, which have a nested model called elements.

storage:

has_many :orders has_many :items, :dependent => :destroy accepts_nested_attributes_for :items 

Order:

 belongs_to:storage has_many :items, :dependent => :destroy accepts_nested_attributes_for :items 

In the viewing order there is a storage selection cell,

 <%= f.select :storage_id, Storage.all.map{|s| [s.store_no, s.id]} %> 

When choosing a storage number, the corresponding items should appear in the Orders form with partial whether any body can tell me the best way to do it.

Thanks,

+6
source share
1 answer

First you need to see that the input field has changed to see it. So, assuming:

  • The storage selector has a storage identifier
  • The store selector has a "store" identifier as its value

... you can put this in your storage.coffee.js file:

 jQuery -> $('select#storage').change -> storage_id = $('option:selected',this).val() $.get 'storages/' +storage_id+ '/orders.js' 

Then, assuming that Orders are nested, if your OrdersController looks like this:

 OrdersController < ApplicationController def index @storage = Storage.find(params[:storage_id]) @orders = @storage.orders end end 

... and if you have a partial app/views/orders/_order.html.erb ...

... and if your page has a div#orders in which you want orders to fall in ...

... then you should make the file app/views/orders/index.js.erb as follows:

 $('div#orders').html('<%= escape_javascript(render @orders) %>'); 

This should make a partial copy for each instance of orders belonging to this repository and add it to dom after the repository selector.

What happens: when you change the selection menu, it starts a js GET request in the order index for this store. Then this request will automatically try to serve the index.js page, and the instance variables set in the controller are available for this view. Js in this view will be executed after any interpolated ruby ​​is inserted, so you can use the rail functions (e.g. render @orders ) and then output those that are injected into dom via $('div#orders').html('your rendered orders will be inserted in here by rails') .

It is clear that you will need to configure it to fit your page, I just guess what elements of your page cause, etc., but this basic concept should work fine. Let me know if you have any questions.

+7
source

Source: https://habr.com/ru/post/913724/


All Articles