-->

Rails 4 Best in place select collection

2019-07-20 06:24发布

问题:

I can not seem to find a answer to my question anywhere, so please help me if anyone can I am trying to understand this better.

I have a method that passes variables into another model's method to get packlist_id's from a table. such as in my invoices model i have:

def packlistid
  Shipperline.packlist(@customerid, @shipqty)
end

The customerid is from another method in my Invoice class (which works amazing) and the shipqty is also from another method query that i did.

Then that method goes into Shipperline model which has a method self.packlist(customerid, shipqty):

def self.packlist(customerid, shipqty)
  Shipperline.joins(:customerorderline, :shipper).select("cust_order_id").where(cust_order_id:      customerid).pluck(:packlist_id).uniq
end

Then in my view i have:

best_in_place invoice, :packlsitid, :as => :select, :class=>"best_in_place", :collection => invoice.packlistid

This is great cause i get a drop do select box filled with numbers such as

76433

53422

43156

34231

However, when i select one such as the 76433 the value that goes into the database is a 1. Where i want it to be the exact same value 76433.

The 53422 when select puts a value of 2 in the database and so on.

This is rails 4 with best in place version 3.0.1

If anyone can help me i would greatly appreciate it.

回答1:

You can see on the code that builds the options for the select that it will always generate a hash with integer keys that will start from 1. That way, you'd have to map it back to the actual value on the server, by generating the same collection and picking the result from the selected index - 1, so in your controller

@selected_packlistid = @invoice.packlistid[params[:packlsitid] - 1]

Which can be a bit cumbersome, specially if there's a chance that #packlistid result has changed in the meantime. So, I'd recommend you to rely on this other piece of the helper code which states that when the collection of values passed is not an array, it just preserves the collection. Then what you need to do is to generate the packlistid and transform it in a hash where the keys and values are the same

list = @invoice.packlistid
@select_values = Hash[list.zip(list)]

and then pass it on to the helper as

best_in_place invoice, :packlistid, collection: @select_values

as the :collection option will be used as seen here. Notice that it expects that the attribute passed on as the second argument to the helper to return the value that should be marked, as you can see here when the method is called, and here when it is setup as the display value.