Note that there are some explanatory texts on larger screens.

plurals
  1. POImporting associated models from single csv in rails 3
    primarykey
    data
    text
    <p>I've been following rails cast episode, <a href="http://railscasts.com/episodes/396-importing-csv-and-excel?view=asciicast" rel="nofollow noreferrer">Importing CSV and excel</a>, but I have a slightly different setup.</p> <p>I have two models, usage(amount) &amp; price(amount). I have it set up so usage has_one price and price belongs_to a usage. In my csv, I have two columns, like so:</p> <pre><code>usage,price 1000,0.1 1500,0.11 </code></pre> <p>I'm trying to import the data so that I can get usage.amount &amp; usage.price.amount into my database. </p> <p>I had a look <a href="https://stackoverflow.com/questions/14642121/when-importing-a-csv-how-do-i-handle-data-in-a-row-that-corresponds-to-an-assoc?rq=1">here</a>, and tried everything there. One thing to note is that I don't have an id column (although I tried with an id column and the code from that question still didn't work).</p> <p>Here is the code from my model:</p> <pre><code>class Usage &lt; ActiveRecord::Base has_one :price, dependent: :destroy accepts_nested_attributes_for :price def self.import(file) CSV.foreach(file.path, headers: true) do |row| Usage.create! row.to_hash end end end </code></pre> <p>Note: I know the above has no reference to importing the price.amount, but anything I tried wouldn't work.</p> <p>Any help on this would be greatly appreciated, thanks!</p> <p><strong>Update</strong></p> <p>Here's how I got it working: (Thanks to <strong>alalani</strong> for helping with the following code.)</p> <pre><code>CSV.foreach(file.path, headers: true) do |row| u = Usage.create(amount: row[0]) u.create_price(amount: row[1]) end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload