[Rails] Re: importing .csv file from user and storing data of csv into database using ruby on rails.
Ruby on Rails
Friday, August 28, 2015
Correction: obviously class Question < ActiveRecord::Base
On Friday, August 28, 2015 at 10:15:07 AM UTC-4, Elizabeth McGurty wrote:
-- On Friday, August 28, 2015 at 10:15:07 AM UTC-4, Elizabeth McGurty wrote:
def import
@question = Question.new ## You have just created a new instance of model class Question
@question.import(params[:file])
redirect_to root_url, notice: "Questions imported succefully."
end
class Question
validates :id, uniqueness: true ## see below
def self.import(file)
CSV.foreach(file.path, headers: true) do |row| ## okay so you will iterate by row
question_hash = row.to_hash
## This is okay, but you should put a watch on row, and understand its structure. In doing so, you may not need to convert row to row.to_hash. Otherwise, you should put a watch on row.to_hash to verify that the
## structure of the 'row' is consistent with your database structure and other matters that may be in your Question model
##@question = Question.where(id: question_hash["id"])
## okay this seems reasonable but at the model level rather than creating a new Question object, you should rather be doing validation on id, see above.
## If I were you I would do validation on the record, not just the id
## if @question.count == 1
##@question.first.update_attributes(question_hash) ## self not new instance of Question
@return_value_on_update_attributes = self.update_attributes( question_hash) ## Read: http://apidock.com/rails/ ActiveRecord/Base/update_ attributes
unless @return_value_on_update_attributes ## unless @return_value_on_update_ attributes is false, eg, if not true
puts "There was an error in record " + question_hash["id"]
puts self.errors.to_yaml ## This way you can continue, and then later you need to check for errors. Of course there are other ways to manage and learn errors. But for now...
end # end unless
end # end foreach
end # end self.import(file)
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/638b60df-6217-409f-a91f-a280a3bc3704%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment