In this post, slice function is used to get only necessary elements of params. What would be the function I should use to exclude an element of params (such as user_id)?
Article.new(params[:article].slice(:title, :body))
Thank you.
Use except:
a = {"foo" => 0, "bar" => 42, "baz" => 1024 }
a.except("foo")
# returns => {"bar" => 42, "baz" => 1024}
Inspired in the sourcecode of except in Rails' ActiveSupport
You can do the same without requiring active_support/core_ext/hash/except
# h.slice( * h.keys - [k1, k2...] )
# Example:
h = { a: 1, b: 2, c: 3, d: 4 }
h.slice( * h.keys - [:b, :c] ) # => { a: 1, d: 4}
Try this
params = { :title => "title", :other => "other", :body => "body" }
params.select {|k,v| [:title, :body].include? k } #=> {:title => "title", :body => "body"}
Considering only standard Ruby.
For Ruby versions below 3, no.
For Ruby 3, yes. You can use except.
Related
How would I save this array in one call with Rails?
tax_rates = [{
:income_from => 0
:income_to => 18200
:start => "01-07-2013"
:finish => "30-06-2014"
:rate => nil
:premium => nil
},{
:income_from => 18201
:income_to => 37000
:start => "01-07-2013"
:finish => "30-06-2014"
:rate => 0.19
:premium => nil
},{
:income_from => 18201
:income_to => 37000
:start => "01-07-2013"
:finish => "30-06-2014"
:rate => 0.19
:premium => nil
}]
Can I just call Rails.create(tax_rates)?
Also, is there a way to remove duplicate symbols so they look neater?
Your example is almost correct.
Use ActiveRecord::Persistence#create, which can accept an array of hashes as a parameter.
tax_rates = [
{
income_from: 0,
income_to: 18200,
start: "01-07-2013",
finish: "30-06-2014",
rate: nil,
premium: nil,
},
{
income_from: 18201,
income_to: 37000,
start: "01-07-2013",
finish: "30-06-2014",
rate: 0.19,
premium: nil,
},
# ...
]
TaxRate.create(tax_rates) # Or `create!` to raise if validations fail
A nice solution is to use the active record import gem. I recommend it over now built-in Rails bulk insert because it's more flexible in the options in case of constraint violation.
TaxRate.import(
[:income_from, :income_to, :start, :finish, :rate, :premium],
tax_rates
)
Its definitely better than my old answer which would trigger a db commit per entry in the array :)
Old answer:
tax_rates.map {|tax_rate| TaxRate.new(tax_rate).save }
This way you'll retrieve an Array with true or false to know which did succeed and which didn't.
If you want all of them to be saved .or, non of them to be saved even if one fails, you can use 'ActiveRecord::Base.transaction'
e.g.
ActiveRecord::Base.transaction do
tax_rate.each do |tax_rt|
TaxRate.new(tax_rt).save
end
end
I am not sure about rails < 4.2 but I have tried it in rails 4.2 you can simply do this
TaxRate.create(tax_rt)
Here is an example like yours:
a = []
a << B.new(:name => "c")
a << B.new(:name => "s")
a << B.new(:name => "e")
a << B.new(:name => "t")
The array is saved all at once with:
a.each(&:save)
This will call B#save on each item in the array.
use a gem 'fast_inserter': https://github.com/joinhandshake/fast_inserter
it generates a single sql query of thousand records.
movie_data = [1, 'Climates (Iklimler)', 'Clay Pauwel', 'Drama'],
[2, 'Tinpis Run', 'Andros Glazer', 'Comedy'],
[3, 'Naked City, The', 'Bethena Chatband', 'Mystery'],
[4, 'Small Time Crooks', 'Naomi Plom', 'Crime'],
[5, 'Shadowboxer', 'Georgeanne Widdicombe', 'Thriller']
params = {
table: 'movies',
static_columns: {
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00',
},
options: {
timestamps: false,
unique: true,
check_for_existing: true
},
group_size: 100,
variable_columns: %w(id title director description),
values: movie_data
}
inserter = FastInserter::Base.new(params)
inserter.fast_insert
Is there a simple way in Ruby 2/Rails 3 to transform this:
{a: {b: {"1" => 1, "2" => 2}, d: "Something"}, b: {c: 1}}
into this:
{"a.b.1" => 1, "a.b.2" => 2, "a.d" => "Something", "b.c" => 1}
I'm not talking about this precise hash but transform any hash into a dot-notation hash.
Here's the cleanest solution I could come up with right now:
def dot_it(object, prefix = nil)
if object.is_a? Hash
object.map do |key, value|
if prefix
dot_it value, "#{prefix}.#{key}"
else
dot_it value, "#{key}"
end
end.reduce(&:merge)
else
{prefix => object}
end
end
Test:
input = {a: {b: {"1" => 1, "2" => 2}, d: "Something"}, b: {c: 1}}
p dot_it input
Output:
{"a.b.1"=>1, "a.b.2"=>2, "a.d"=>"Something", "b.c"=>1}
Say I have this:
[
{ :user_id => 1, :search_id => a},
{ :user_id => 1, :search_id => b},
{ :user_id => 2, :search_id => c},
{ :user_id => 2, :search_id => d}
]
and I want to end up with:
[
{ :user_id => 1, :search_id => [a,b]},
{ :user_id => 2, :search_id => [c,d]}
]
What is the best way to do that?
Very strange requirement indeed. Anyway
[ { :user_id => 1, :search_id => "a"},
{ :user_id => 1, :search_id => "b"},
{ :user_id => 2, :search_id => "c"},
{ :user_id => 2, :search_id => "d"} ] \
.map{ |h| h.values_at(:user_id, :search_id) } \
.group_by(&:first) \
.map{ |k, v| { :user_id => k, :search_id => v.map(&:last) } }
array.group_by{|x| x[:user_id] }.values.map do |val|
{ user_id: val.first[:user_id],
search_id: val.inject([]){|me, el| me << el[:search_id]} }
end
First off, I think the cleaner output structure here is to allow the user IDs to be the hash keys and the list of search IDs to be the values:
{
1 => [a, b],
2 => [c, d]
}
There might be a clever way using Rails helpers to get this structure, but it's not too bad to do it manually, either:
output = {}
input.each do |row|
key = row[:user_id]
value = row[:search_id]
output[key] ||= []
output[key] << value
end
I agree with Matchus representation of the data and just want to suggest a shorter version for it (input being the initial array).
input.each.with_object(Hash.new {|h,k| h[k] = []}) do |k,o|
o[k[:user_id]] << k[:search_id]
end
EDIT: this is Ruby > 1.9
input.inject({}) do
|m, h| (m[h[:user_id]] ||= []) << h[:search_id]; m
end.inject([]) { |m, (k, v)| m << { :user_id => k, :search_id => v }; m }
This is what I've been getting:
{:user=>{:employees=>{...}, :login=>"dernalia", :id=>1, :role=>2}}
What is generating the hash:
def management_tree(args = {})
args = {:users => [], :result => {}}.merge(args) #defaults
result = args[:result]
if not args[:users].include? self.login #prevent duplicates
result.merge!({:user => {:id => self.id,
:login => self.login,
:role => self.role,
:employees => employee_tree(args[:users] + [self.login], args[:result])
}
})
end
logger.info result.inspect
return result
end
def employee_tree(users, result)
if self.employees.length > 0
self.employees.each {|emp| (emp.management_tree({:users => users, :result => result})) }
end
return result
end
Now... it's supposed to return something like this:
{:user=>{:login=>"me", :id=>1, :role=>2,
:employees=>{
:user => {:login => "2", ...},
:user => {:login => "3",
:employees => {...}
}
}}
Some console output:
% bundle exec script/console
Loading development environment (Rails 2.3.8)
>> require "awesome_print"
=> []
>> ap User.find(1).management_tree[:employees]
nil
=> nil
>> ap User.find(1).management_tree
{
:user => {
:employees => {...},
:role => 2,
:login => "me",
:id => 1
}
}
=> {:user=>{:employees=>{...}, :role=>2, :login=>"me", :id=>1}}
>>
now... it says that employees is nil... but it shouldn't be... it should have 3 hashes ... =\
but also, what does {...} mean? it seams terribly ambiguous
Ruby is clever about recursive structures and will use "..." instead of looping indefinitely.
For example:
a = [1, 2]
a << a # a is now recursive, since it contains itself
a.to_s # => [1, 2, [...]]
a[2][2][2][2][2][2][2] == a # => true
In your case, the {...} refers to any of the hashes already in the process of being outputed.
Maybe what you meant to do was to insert a copy of a hash? In the simple array example:
a = [1, 2]
a << a.dup # a is not recursive
a.to_s # => [1, 2, [1, 2]]
I have a Hash which is of the form
{:a => {"aa" => 11,"ab" => 12}, :b => {"ba" => 21,"bb" => 22}}
How do i convert it to the form {:a => [["aa",11],["ab",12]],:b=>[["ba",21],["bb",22]]}
If you want to modify the original hash you can do:
hash.each_pair { |key, value| hash[key] = value.to_a }
From the documentation for Hash#to_a
Converts hsh to a nested array of [
key, value ] arrays.
h = { "c" => 300, "a" => 100, "d" => 400, "c" => 300 }
h.to_a #=> [["c", 300], ["a", 100], ["d", 400]]
Here is another way to do this :
hsh = {:a => {"aa" => 11,"ab" => 12}, :b => {"ba" => 21,"bb" => 22}}
hsh.each{|k,v| hsh[k]=*v}
# => {:a=>[["aa", 11], ["ab", 12]], :b=>[["ba", 21], ["bb", 22]]}
hash.collect {|a, b| [a, hash[a].collect {|c,d| [c,d]}] }.collect {|e,f| [e => f]}