I need to tie the current user with the json response that I am capturing and storing in PostgreSql 9.4. I am using Rails 4. I am able to successfully store the json in a column 'return' of json data type. I have taken measures to create the model associations and updated the schema, and I have a user model with a record but the user_id remains nil in the Document record holding the json return. I list the controller as I'm nearly convinced that my problem is here.
require 'alchemyAPI/alchemyapi'
require 'json'
class AlchemyController < ApplicationController
def index
#documents = Document.all
end
def create
alchemyapi = AlchemyAPI.new()
response = alchemyapi.combined('url', params[:q], {'extract'=>'page-image, title, author, concept' })
puts JSON.pretty_generate(response)
if
Document.create(result: response)
flash[:notice] = "Input was successfully analyzed and persisted."
redirect_to action: 'index'
else
flash[:notice] = "Input was successfully analyzed and persisted."
redirect_to action: 'index'
end
end
end
Solution was for me to add the current user as depicted in the first two lines of the if block.
def create
alchemyapi = AlchemyAPI.new()
response = alchemyapi.combined('url', params[:q], {'extract'=>'page-image, title, author, concept' })
puts JSON.pretty_generate(response)
if
*#user = current_user*
*#user.documents.create(result: response)*
flash[:notice] = "Input was successfully analyzed and persisted."
redirect_to action: 'index'
else
flash[:error] = "There was a problem analyzing your input."
redirect_to action: 'index'
end
end
Related
I did a date validation in model which should display a message on page, but for some reason it isn't. I need this message to be shown in notice on error. Currently I just see the message in controller (Order not registered) but I need to see the reason (Delivery date should be from now). How can I do that?
model
def delivery_date_from_now_only
if self.delivery_date.present? && self.delivery_date <= Date.today
self.errors.add(:delivery_date, messsage: 'Delivery date should be from now')
end
end
controller
def create
#order = Order.new(order_params)
#order.user = current_user
if #order.save
flash[:notice] = 'Order registered successfully'
return redirect_to #order
end
#warehouses = Warehouse.all.order(:name)
#suppliers = Supplier.all.order(:brand_name)
#users = User.all.order(:name)
flash.now[:alert] = 'Order not registered'
render :new, status: 422
end
if you call #order.valid? it will validate your model an also populate errors for that object. that means #order.errors.messages will be a hash with { :delivery_date => ["Delivery date should be from now"]} etc (other errors will be in there as well) which u can use to do some flashes.
In my controller action PagesController#transfer I would like to download an xml document, then reload the page.
But the xml document is generated with render_to_string so I get an error when I try to add a redirection after downloading the file.
The goal of this is to get a flash message after downloading the XML. So reloading the page seems to be a good option.
pages_controller
def transfer
...
multiple_export_to_sepa(objects, #errors)
end
private
def multiple_export_to_sepa(objects, errors)
sepa_filename = "virements_#{params[:type]}.xml"
if objects.present?
stream = render_to_string(template: "admin/pages/transfers_#{params[:type]}.xml", layout: false)
send_data(stream, type: 'text/xml', filename: sepa_filename , status: :created)
flash[:success] = "#{objects.length} objects has been generated."
redirect_to action: :transfer
else
redirect_to action: :transfer
end
end
Have you tried using flash.now?
def multiple_export_to_sepa(objects, errors)
sepa_filename = "virements_#{params[:type]}.xml"
if objects.present?
stream = render_to_string(template: "admin/pages/transfers_#{params[:type]}.xml", layout: false)
send_data(stream, type: 'text/xml', filename: sepa_filename , status: :created)
flash.now[:success] = "#{objects.length} objects has been generated."
else
redirect_to action: :transfer
end
end
From the docs(http://guides.rubyonrails.org/action_controller_overview.html#flash-now):
5.2.1 flash.now
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:
class ClientsController < ApplicationController
def create
#client = Client.new(params[:client])
if #client.save
# ...
else
flash.now[:error] = "Could not save client"
render action: "new"
end
end
end
I am trying to save data from calling the Linkedin API in my rails app, but when it goes to save I get the error:
TypeError: can't cast LinkedIn::Mash to text
I do not want the user to edit the information either, so I set the information in the NEW controller as follows:
def new
#client = LinkedIn::Client.new
#client.authorize_from_access(current_user.consumer_token, current_user.consumer_secret)
#resume = Resume.new do |u|
u.location = current_user.location
u.picture_url = current_user.image_url
u.summary = #client.profile(:fields => %w(summary))
u.work_experience = #client.profile(:fields => %w(positions))
u.education = #client.profile(:fields => %w(educations))
u.user = current_user
end
#resume.save!
if #resume.save
flash[:succes] = "Resume Saved!"
redirect_to resumes_path
else
flash[:error] = "Resume did not save."
redirect_to resumes_path
end
end
Is that considered bad practice? Should I set the save in the create controller? How about the TypEerror? I feel like since I am saving the information straight from the API that it can't be saved as plain test.
This is what your config/routes.rb should look like:
resources :resumes
This is the #create method in your controller.
def create
#resume = Resume.new(params[:resume]) # if you are on rails 4 then you have to use strong params
if #resume.save
flash[:succes] = "Resume Saved!"
redirect_to resumes_path
else
flash[:error] = "Resume did not save."
redirect_to resumes_path
end
end
The #create method is a post naturally. This resource is very helpful for understanding routes. http://guides.rubyonrails.org/routing.html. As to your question regarding the mash, I do think it has been answered here How to parse a Mash from LinkedIn to create a Ruby object.
I have a belonging model that allows user to post objects to be sold or rented on my website. I recently changed the form, making it a multi-step form: a first form asks the name of the object and if the object is for sale or to rent, a second form ask for object's details, with the fields depending on the user's choice.
I am using is_taggable, with Rails 3.0.5, and my problem is that tag_list is never saved in the database since I switched to the multi-step form (all the other fields are saved correctly).
I followed Ryan Bates Rails cast #217.
Before, I was using: #belonging.tag_list = params[:belonging][:tag_list]
Since I went from multistep, I am using: #belonging.tag_list = session[:belonging_params][:tag_list]
I am a bit of a newbie in Rails, so there might be something obvious I am missing here. I spent the whole afternoon and evening trying to understand what is wrong, any help will therefore be appreciated!
Here are the 'new' and 'create' action of my controller:
class BelongingsController < ApplicationController
before_filter :authenticate_user!, :except => [:index, :with_tag, :remove_tag]
after_filter :update_tag_cloud, :only => [:create, :update]
def new
#title = "Insert a new product or service"
#user = current_user
session[:belonging_params] ||= {}
session[:belonging_step] = nil
#belonging = #user.belongings.new(session[:belonging_params])
session[:belonging_params][:tag_list] ||= []
#belonging.current_step = session[:belonging_step]
render 'new'
end
def create
session[:belonging_params].deep_merge!(params[:belonging]) if params[:belonging]
#belonging = current_user.belongings.build(session[:belonging_params])
#belonging.current_step = session[:belonging_step]
#belonging.tag_list=session[:belonging_params][:tag_list]
if params[:previous_button]
#belonging.previous_step
render 'new'
elsif params[:cancel_button]
session[:belonging_step] = session[:belonging_params] = nil
redirect_to user_path(current_user)
elsif params[:continue_button]
if #belonging.last_step?
if #belonging.save!
expire_fragment('category_list')
flash[:success] = "New product or service created!"
session[:belonging_step] = session[:belonging_params] = nil
redirect_to belonging_path(#belonging)
else
flash[:error] = "Object could not be saved"
render 'new'
end
else
#belonging.next_step
render 'new'
end
else
render 'new'
end
session[:belonging_step] = #belonging.current_step
end
Many many thanks for any clue !!
I actually thought that:
session[:belonging_params].deep_merge!(params[:belonging]) if params[:belonging]
would copy everything inside params[:belonging] but it seems that params[:belonging][:tag_list] was not copied into session[:belonging_params][:tag_list] as I expected ...
So the problem was solved by adding in the 'create' action a new session variable:
session[:tag_list] = params[:belonging][:tag_list] to be able to save :tag_list from a step of the form to the next.
session[:tag_list] is defined first in the 'new' action as:
session[:tag_list] ||= []
This is the field on form, I am using
<%= f.file_field :file ,:url=>{:controller=>"retailers",:action=>"csv_import"}%>
The following is the controller code
def create
#retailer = Retailer.new(params[:retailer])
respond_to do |format|
if verify_recaptcha(:model =>#retailer ) && #retailer .save
# To notify newly registered user.
retailer_ids = [#retailer.id]
Emailer.on_notify_retailer(retailer_ids, 1, 0)
sign_in #retailer
format.html { redirect_to pages_about_path}
flash[:notice1] = "Thank you for registering with Chindi."
flash[:notice2] = "We will process your application and get back to you within 48 hours. Once approved, you will be able to create negotiable deals that Consumers can tailor to their needs."
flash[:notice3] = "You will be able to create, manage and administer your deals and your buyers in this easy to use control panel."
format.json { render json: pages_about_path, status: :created, location: #retailer }
else
#title = "Sign up"
format.html { render action: "new"}
flash[:notice1] = "Incorrect word verification. Are you sure you\'re human?"
format.json { render json: #retailer.errors, status: :unprocessable_entity }
end
end
csv_parse()
end
The above code is used to save the data into database. The CSV file #retailer.file_file_name is to be stored in database as well as it needs to be parsed and the values need to be stored in fields
csv_parse is used to parse the csvfile
I am able to save file in data
now i need to parse the csv file and store the individual fields in another database.
the code for csv_parse is as follows.
def csv_parse
#parsed_file=CSV.foreach(params[:dump][:file].original_filename)
n=0
#parsed_file.each do |row|
User_list.create(
:email=>row[0],
:first_name=>row[1],
:last_name=>row[2]).save
flash.now[:message]="CSV parse Successful, #{n} new records added to data base"
end
end
when I run this it gives the following error/s.
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
please help me with the above error why is it throwing such an error
thanks in advance.
I just paste some peace of working for me code and hope it will help you:
first_line = true
file = File.open File.join(Rails.root, 'tmp/import/category.csv')
file.each do |line|
unless first_line
row = CSV::parse_line(line, ';')
category = Category.find_by_name(row[1]) || Category.create(:name => row[1], :target => 'basic')
category.update_attribute(:import_id, row[0])
else
first_line = false
end
end
I sometime wrote this code to import categories to my DB. Here you can change CSV file name and block for each iterator. Also first_line is description for fields and I was ignoring it.
def create
#retailer = Retailer.new(params[:retailer])
respond_to do |format|
# ... same as above
end
csv_parse(params[:retailer][:file].path)
private
def csv_parse(path)
rows = CSV.read(path)
rows.each do |row|
User_list.create(:email=> row[0], :first_name=>row[1], :last_name=>row[2])
end
flash.now[:message]= "CSV parse Successful, #{rows.size} new records added"
end
end