I have a Rails form that has two types of nested attributes: Pendencies and Address.
However, those two are not obligatory fields and should be ignored when blank:
accepts_nested_attributes_for :pendencies, allow_destroy: true,
reject_if: proc { |attributes|
attributes['status'].blank? &&
attributes['description'].blank? &&
(attributes['pendency_type'].blank? || attributes['pendency_type'] == 0) }
accepts_nested_attributes_for :address, allow_destroy: true,
reject_if: proc { |attributes|
attributes['zipcode'].blank? &&
attributes['street'].blank? &&
(attributes['number'].blank? || attributes['number'] <= 0) &&
attributes['neighbour'].blank? &&
attributes['city'].blank? &&
attributes['state'].blank? }
I have used binding.pry on both procs to ensure they are running and they are. Both are returning true or false as expected.
Yet, once the model which hold those associations gets validated when calling model.update, it returns errors about the exactly same fields it should be ignoring:
#messages=
{:"pendencies.status"=>["não pode ficar em branco"],
:"pendencies.description"=>["não pode ficar em branco"],
:"pendencies.pendency_type"=>["não pode ficar em branco"],
:"address.zipcode"=>["não pode ficar em branco", "não é válido", "não possui o tamanho esperado (8 caracteres)"],
:"address.street"=>["não pode ficar em branco", "é muito curto (mínimo: 3 caracteres)"],
:"address.number"=>["não pode ficar em branco", "não é um número", "é muito curto (mínimo: 1 caracteres)"],
:"address.city"=>["não pode ficar em branco", "é muito curto (mínimo: 2 caracteres)"],
:"address.state"=>["não pode ficar em branco", "é muito curto (mínimo: 2 caracteres)"]}>
Sorry for the PT-BR in the messages, all it says is that the length is short and the field is invalid.
I would like to know how can I ignore those nested attributes so Rails would not try to save them.
Thank you.
Related
I am trying to convert user input à la "6 months" into a Ruby method à la 6.months.
How can this be done?
I keep getting an undefined method 6.months error in line 10.
Thanks for any help.
class Coupon < ActiveRecord::Base
def self.duration_options
["3 years", "2 years", "1 year", "6 months", "3 months", "1 month"]
end
def end_at
if Coupon.duration_options.include?(duration)
method = duration.sub!(' ', '.')
time = Time.zone.now + send(method)
end
time
end
end
Your send is on the object itself, in this case it's self.send(method)
You could do like this
if Coupon.duration_options.include?(duration)
off_set = duration.split(" ")
time = Time.zone.now + off_set.first.to_i.send(off_set.last.to_sym)
end
time
When I enter a price more than three digits, such as 1000, the js script makes the 1 000, 10 000, etc. It puts a space for the user's convenience. Validation display is not a numeric type. How convert to int type in this situation?
validates :price, numericality: { only_integer: true, allow_nil: true }
here is a slightly better solution that would still allow you to have nil values
(please note that nil.to_i is 0 as well as any "text".to_i is also 0)
def my_method(str)
Integer(str.gsub(/\s/, ''))
rescue ArgumentError => e
nil
end
Example of use:
my_method('1000')
=> 1000
my_method('1 000')
=> 1000
my_method(' ')
=> nil
my_method('some_text')
=> nil
my_method('1.000')
=> nil
my_method('1,000')
=> nil
If you want to treat . and , you can adapt the regex in gsub.
I found a solution:
2.3.0 :004 > "1 000".delete(' ')
=> "1000"
2.3.0 :005 > "1 000".delete(' ').to_i
=> 1000
I'm actually trying to use Json, from open data paris, and to filter some stuff.
I can create what I want with those lines:
def import
#result = ''
url = 'http://opendata.paris.fr/api/records/1.0/search/?rows=1000&dataset=arc_innovation&facet=code_postal&facet=commune&facet=etat_1&facet=typologie_carto&facet=type_innovation&facet=image'
response = HTTParty.get(url)
hash = response.parsed_response
hash['records'].each do |record|
lime = Lime.where(datasetid: record['datasetid'], recordid: record['recordid']).first_or_initialize
lime.title = record['fields']['nom']
lime.text = record['fields']['txt_descriptif']
lime.url = record['fields']['site_internet']
lime.xy = record['fields']['xy']
category = category_from_typeinnovation(record['fields']['type_innovation'])
lime.categories << category unless category.nil?
if record['fields'].has_key? 'image'
image_id = record['fields']['image']['id']
image_filename = record['fields']['image']['filename']
image_url = "http://opendata.paris.fr/explore/dataset/arc_innovation/files/#{image_id}/download"
lime.image = image_url
end
lime.save
#result += "imported #{lime.title}\n"
end
render text: #result
end
Here is how looks my Json like
"records":[
{
"fields":{
"commune":"Paris 19e",
"code_postal":75019,
"id_formularie":1,
"etat_1":"existant",
"contact_tel":"01 53 35 50 00",
"xy":[
48.889979,
2.371504
],
"nom":"104",
"txt_descriptif":"Plateforme collaborative qui s’intéresse à la création artistique contemporaine dans toute sa diversité, elle accueille des artistes en résidence et accompagne l’émergence de nouvelles formes d’art avec le Cinq destiné aux pratiques amateurs, la Maison desPetits et un incubateur qui héberge et soutient le développement de start-ups.",
"type_innovation":"Lieux innovants de la culture et du sport",
},
I try to filter by "type-innovation". I don't want to create a post with the data that own "type_innovation":"Lieux innovants de la culture et du sport" for example.
I tried to filter like this:
def import
#result = ''
url = 'http://opendata.paris.fr/api/records/1.0/search/? rows=1000&dataset=arc_innovation&facet=code_postal&facet=commune&facet=etat_1&facet=typologie_carto&facet=type_innovation&facet=image'
response = HTTParty.get(url)
hash = response.parsed_response
hash['records'].each do |record|
lime = Lime.where(datasetid: record['datasetid'], recordid: record['recordid']).first_or_initialize
lime.title = record['fields']['nom']
lime.text = record['fields']['txt_descriptif']
lime.url = record['fields']['site_internet']
lime.xy = record['fields']['xy']
category = category_from_typeinnovation(record['fields']['type_innovation'])
lime.categories << category unless category.nil?
if record['fields'].has_key? 'image'
image_id = record['fields']['image']['id']
image_filename = record['fields']['image']['filename']
image_url = "http://opendata.paris.fr/explore/dataset/arc_innovation/files/#{image_id}/download"
lime.image = image_url
end
if record['fields']['type_innovation'] != ['fields']['type_innovation']['Lieux innovants de la culture et du sport']
lime.save
#result += "imported #{lime.title}\n"
end
end
render text: #result
end
When I try to import it returns me the error. How Should I do the filtering?
My problem is that I need to fill an array with rails 4 to display top 3 results categorized by newspaper
Category of newspaper is: 0,1,2,3 or other, is random.
parsed_json: Is one array with values de newspapers, after news_source fill with news from newspapers.
SQL: http://i.stack.imgur.com/dP8BM.png
With this code only the last value of the array of a newspaper.
def index
if get_api_key
#parsed_json = Array.new
#news_source = Array.new
#Trae todos los datos asociados a la llave
#emission = Emission.where(key: get_api_key)
#Envío de datos a json
#emission.each do |p|
#weather_now = WeatherNowUy.where(city: p.state)
#weather_next_days = WeatherNextDaysUy.where(city: p.state)
#parsed_json << JSON.parse(p.news_source)
end
#parsed_json.each do |u|
#news_source = NewsUy.where(newspaper: u).limit(3)
end
end
end
Example of return, no show by newspaper 1 is also found in the array parsed_json.
Not
"News": [
{
"title": "Con un gol de Tevez, Boca venció a Godoy Cruz 2-0 y sigue en lo más alto",
"description": "El delantero marcó de penal en la victoria en La Bombonera. Meli habÃa abierto el marcador. Los \"Xeneizes\" comparten con San Lorenzo la primera posición.",
"newspaper": "0"
},
{
"title": "Barcelona picó en punta",
"description": "La primera fecha del fútbol español se terminará el lunes con el partido entre Granada y Eibar.",
"newspaper": "0"
},
{
"title": "Sampdoria, Chievo Verona y Fiorentina los lÃderes",
"description": "Este fin de semana se disputó la primera fecha de la serie A italiana.",
"newspaper": "0"
}
]
}
Change #news_source = NewsUy.where(newspaper: u).limit(3) to #news_source << NewsUy.where(newspaper: u).limit(3) in your last #parsed_json.each do loop. Because, if you use = operator, it will replace it every time with the next value and that's why you are getting only the last value. To get all the values, you need to accumulate those into the #news_source array using << operator.
So, you need this:
#parsed_json.each do |u|
#news_source << NewsUy.where(newspaper: u).limit(3)
end
there is possible to related a related field ?
I did
1st object
_columns = {
'sale_price_unit': fields.related('sale_line_id','price_unit',string='Prix de vente',type='float', store=True, readonly=True),
}
the other object
_columns={
'sale_price_unit': fields.related('procurement_id','sale_price_unit',string='Prix de vente',type='float', store=True, readonly=True),
}
the value of the 2nd object alwayse equal 0.0 !!
try
_columns={
'sale_price_unit': fields.related('procurement_id','sale_line_id','price_unit',string='Prix de vente',type='float', store=True, readonly=True),
}