Rails 3.1 Remote Link writing to the DB 5 times. - ruby-on-rails

I Have a remote link that when clicked sends an ajax request to a controller action in the background. This request creates a new database entry. The problem is that it currently writes to the database 5 times for each click.
Here is my link and controller action:
click
def track_link
y = cookies[:user_email]
x = User.where(email: y).first
z = x.id
name = params[:link_name]
w = Link.new
w.name = name
w.user_id = z
w.save
respond_to do |format|
format.js { render action: "index" }
end
end

Your jquery_ujs file is probably being included 5 times.

Related

how to remove duplicacy in database when importing csv file into app that using spree gem

i am using spree gem in my app. I import products from product_controller_decorator.rb using csv file.Three tables like spree_products,spree_variants and
spree_prices are relation. As #prod.save happen then it create one row in spree_products,one in spree_variants and one in spree_prices. then another
spree_variants and spree_prices row form due to #var and #price for corresponding #prod which create duplicacy in both table.This is happens due to
association among three tables.can any one resolve this complicacy.It means it form one row to each table.
def import
require 'csv'
file = params[:file]
CSV.foreach(file.path, headers: true, encoding:'iso-8859-1:utf-8') do |row|
#prod = Spree::Product.new()
#prod.name = row["name"]
#prod.shipping_category_id = row["shipping_category_id"]
#prod.description = row["description"]
#prod.available_on = row["available_on"]
#prod.meta_description = row["meta_description"]
#prod.meta_keywords = row["meta_keywords"]
#prod.tax_category_id = row["tax_category_id"]
#prod.shipping_category_id = row["shipping_category_id"]
#prod.promotionable = row["promotionable"]
#prod.meta_title = row["meta_title"]
#prod.featured = row["featured"]
#prod.supplier_id = row["supplier_id"]
#prod.master.price = row["master_price"]
#prod.save!
#var = Spree::Variant.create(cost_price: row["cost_price"], is_master:1, product_id: #prod.id, sku: row["sku"])
if #var.errors.present?
render json: #var #.errors and return
end
#price = Spree::Price.create(variant_id: #var.id)
if #price.errors.present?
render json: #price #.errors and return
end
end
redirect_to admin_products_path, notice: "products imported."
end
With Spree, the master is created when the product is saved, and the defaults for master is applied to it. Instead of creating a new master variant, #var = Spree::Variant.create, update the master instead. You update the master earlier in the file by assigning #prod.master.price = row["master_price"]. That code isn't failing because master is created with default values before the call to #product.save. The line #price = Spree::Price.create(variant_id: #var.id) Is associating an empty (default) Price with the #prod.master. That is already done, they are supposed to be unique, so there is probably fallout from doing this.
Avoid checking for errors after executing .create. If you want to validate errors, do so before saving. The way to do this is:
#var = Spree::Variant.new(cost_price: row["cost_price"], is_master:1, product_id: #prod.id, sku: row["sku"])
if #var.errors.present?
render json: #var #.errors and return
else #var.save
I would rewrite the block as this:
#prod = Spree::Product.new()
#prod.name = row["name"]
#prod.shipping_category_id = row["shipping_category_id"]
#prod.description = row["description"]
#prod.available_on = row["available_on"]
#prod.meta_description = row["meta_description"]
#prod.meta_keywords = row["meta_keywords"]
#prod.tax_category_id = row["tax_category_id"]
#prod.shipping_category_id = row["shipping_category_id"]
#prod.promotionable = row["promotionable"]
#prod.meta_title = row["meta_title"]
#prod.featured = row["featured"]
#prod.supplier_id = row["supplier_id"]
#prod.master.price = row["master_price"]
#prod.master.sku = row["sku"]
[#prod, #prod.master, #prod.master.price].each do |obj|
render json: obj if obj.errors.present?
end
#prod.save!
Here is the spree-core source: Spree Product Model

Rails rest put HTTP/1.0 501 Not Implemented

I need to use RESTful input to my Rails app. First I'm trying to just understand REST and I'm using WizTools RestClient on my MAC for testing.
I have a table called priorities and I'm trying to update a field called prioritydesc.
This is the info I'm using
METHOD = PUT
URL = http://mywebsite/priorities/4
HEADER = prioritydesc
VALUE = "TEST"
The results I'm getting is:
HTTP/1.0 501 Not Implemented
If I use the resttesttest.com site, I get:
Origin http://resttesttest.com is not allowed by Access-Control-Allow-Origin.
Thanks for the help!
UPDATE1:
Do I need gem "oauth-plugin"?
UDPATE2:
This is my priorities_controller PUT:
# PUT /priorities/1
# PUT /priorities/1.json
def update
#priority = Priority.find(params[:id])
respond_to do |format|
if #priority.update_attributes(params[:priority])
format.html { redirect_to #priority, notice: 'Priority was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: #priority.errors, status: :unprocessable_entity }
end
end
end
UPDATE3
I tried on localhost using:
METHOD = PUT
URL = http://localhost/priorities/1
HEADER = prioritynum
VALUE = 5
And got
"<html><body>You are being redirected.</body></html>"
That seems OK to me.
But, the value didn't update.
UPDATE4
I used this:
METHOD = POST
URL = http://localhost/priorities
HEADER = prioritynum
VALUE = 5
And it added a new record! But, the prioritynum was blank
I also tried using
http://localhost:5000/priorities?prioritynum=5
Should the data field(s) like (prioritynum=5) be in the header or the body?
I put this in the body and it didn't work:
typecode="test"
UPDATE5
OK this worked !!
METHOD = PUT
URL = http://mywebsite/priorities?priority[prioritynum]=5
I got it working for the types controller - I used this:
Method = POST
URL = http://mywesite/types?type[typecode]=test&type[typedesc]=test%20description

is there a DRY way to use strip on all :params when creating a new model in Rails?

I have a form to create a new Contact model.
I enter the values by hand by cutting and pasting.
Sometimes I end up adding white space on the left and right.
Here is what is in the create controller (I have a loop that checks if I have uploaded a vcard which, obviously, doesn't typically present the problem (although it could) -- but my big problem is when I type it myself.
def create
#contact = Contact.create(params[:contact])
unless #contact.vcard.path.blank?
paperclip_vcard = File.new(#contact.vcard.path)
#vcard = Vpim::Vcard.decode(paperclip_vcard).first
#contact.title = #vcard.title
#contact.email = #vcard.email
#contact.first_name = #vcard.name.given
#contact.last_name = #vcard.name.family
#contact.phone = #vcard.telephone
#contact.address.street1 = #vcard.address.street
#contact.address.city = #vcard.address.locality
#contact.address.state = #vcard.address.region
#contact.address.zip = #vcard.address.postalcode
#contact.company_name = #vcard.org.fetch(0)
end
#contact.user_id = current_user.id # makes sure every new user is assigned an ID
if #contact.save
#check if need to update company with contact info
#contact.update_company
#contact.new_todos #create the todos for the newly created contact
flash[:notice] = "Successfully created contact."
redirect_to #contact
else
render :action => 'new'
end
end
This might help: http://scottmoonen.com/2009/05/08/rails-pattern-trim-spaces-on-input/

does a after_created Rails callback method on a model have an instance of the newly created model?

I have a after_create method for my Contact model.
However, when I put the value, it comes out nil. How can I have a callback for a newly created model ( I do a fair amount of transformation in the create model) referenced within the callback method?
after_save :update_company
def update_company
puts self.inspect
puts self.company
if company.phone.empty?
company.phone = self.phone
company.save
end
end
When I look at the logs for self.inspect, it doesn't show any of the transformations used in the create method...yet, this should run only after it has created (and saved), the object, right?
Here is the create method:
def create
#contact = Contact.create(params[:contact])
unless #contact.vcard.path.blank?
paperclip_vcard = File.new(#contact.vcard.path)
#vcard = Vpim::Vcard.decode(paperclip_vcard).first
#contact.title = #vcard.title
#contact.email = #vcard.email
#contact.first_name = #vcard.name.given
#contact.last_name = #vcard.name.family
#contact.phone = #vcard.telephone
#contact.address.street1 = #vcard.address.street
#contact.address.city = #vcard.address.locality
#contact.address.state = #vcard.address.region
#contact.address.zip = #vcard.address.postalcode
#contact.company_name = #vcard.org.fetch(0)
end
#contact.user_id = current_user.id # makes sure every new user is assigned an ID
if #contact.save
flash[:notice] = "Successfully created contact."
redirect_to #contact
else
render :action => 'new'
end
end
Yes, this happens because you didn't use self when assigning the value to company object.
In ruby, generally you don't require the use have "self" to retrieve attributes of an instance
for example in your code. you can puts company and it would work fine.
but when assigning (on the left hand side ) you always have to use self.
so change this in your code.
self.company.phone = self.phone
company.save
or
self.company.phone = phone
company.save

How do I create a call back which runs after the final save in the create method in Rails?

I have the following create method for a Contact controller:
def create
puts "in create method"
#contact = Contact.create(params[:contact])
unless #contact.vcard.path.blank?
paperclip_vcard = File.new(#contact.vcard.path)
#vcard = Vpim::Vcard.decode(paperclip_vcard).first
#contact.title = #vcard.title
#contact.email = #vcard.email
#contact.first_name = #vcard.name.given
#contact.last_name = #vcard.name.family
#contact.phone = #vcard.telephone
#contact.address.street1 = #vcard.address.street
#contact.address.city = #vcard.address.locality
#contact.address.state = #vcard.address.region
#contact.address.zip = #vcard.address.postalcode
#contact.company_name = #vcard.org.fetch(0)
end
#contact.user_id = current_user.id # makes sure every new user is assigned an ID
if #contact.save
#check if need to update company with contact info
#contact.update_company
flash[:notice] = "Successfully created contact."
redirect_to #contact
else
render :action => 'new'
end
end
The callback I want to run should be done after the if #contact.save line at the very end of the method...but right now, it runs it in the first .create.
How do I allow a call back to run only after all the processing in the create method is completed?
Basically, ActiveRecord::Callback create(...) - Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.
You need to use (this is going from your script logic) instead:
#contact = Contact.new(params[:contact])
If you want to callback save, use after_save callback.

Resources