BlueDevilPride BlueDevilPride - 3 months ago 21
Ruby Question

sort imported file ruby

When previously importing my CSV file the data would upload sorted, but now, for no apparent reason, it's not coming out sorted after being uploaded and I'm having difficulty figuring out how to get it to sort.

To fix this, I'm looking at my file upload code and HTML code. I built a dynamic drop down box whereby the user selects a state, which populates the next drop down box with all bank listed in that state by bank name. I need the bank names in the second drop down box to appear alphabetically. Previously, when I uploaded my CSV file, the bank names would appear alphabetically, but now it's not doing that.

Any help would be greatly appreciated. Probably something silly I'm overlooking here.

FDIC MODEL

def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
attributes = row.to_hash
attributes['state'] = State.where(name: attributes['state']).first
Fdic.create! attributes
end
end


HTML

<h4>Select a State</h4>
<%= select_tag :state, options_for_select(State.all.pluck(:name)), include_blank: "States" %>

<h4>Select a Bank</h4>
<%= select_tag :bank, option_groups_from_collection_for_select(@states, :fdic, :name, :id, :bank), include_blank: "Select a Bank" %>

Answer

If I right understand your problem, and if your model State looks like:

class State < ..
    has_many :banks
    etc..
end

This correction should help you, I think.

class State < ..
    has_many :banks, -> { order("banks.name") }
    etc..
end

P.S. If you will use find_by your code would be more clearer)

attributes['state'] = State.find_by(name: attributes['state'])
Comments