I am new at Ruby and Rails and I'm trying to create an array like this:
#data =[
{
order => {key => value, key1 => value1},
folder => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}},
document => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}}
},
{
order => {key => value, key1 => value1},
folder => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}},
document => { 0 => {key => value , key1 => value1}, 1 => {key => value, key1 => value}}
},
]
I have 3 tables, Order, Folder and Document. I have to make a find in Order with certain condition and is going to retrieve some records.
If the find in Order retrieve 3(can be any number) records then I have to make 3 find in Folders and the condition is the Order.id.
Then I have to make a find in Document and the condition is the last Folder.id, this can retrieve many records.
So, I wanna make this so i can send #data to the view and make some foreach for show all the necessary information.
EDIT:
Mudasobwa this is what I try:
Order.where(conditions).find_each do |order|
logger.debug(order.id) #first log
Folder.where(condition order.id).find_each do |folder|
logger.debug(folder.id) #second log
end
Document.where(folder.id).find_each do |doc|
logger.debug(doc.id) #third log
end
end
With this I am getting the info that I want. 1 order.id then all the folders related with that order.id and all the document related with the last folder.id but I dont know how to create the #data array with all this info, how to join everything.
Related
i'm new to ruby and i want to instersect two arrays
validAccountTypes = [
'Asset' => 'Asset',
'Liability' => 'Liability',
'Equity' => 'Equity',
'Income' => 'Income',
'CostOfSales' => 'Cost of Sales',
'Expense' => 'Expenses',
'OtherIncome' => 'Other Income',
'OtherExpense' => 'Other Expenses',
]
types = [
'Asset',
'Other Income',
'Other Expenses',
]
I want a result of valid Accounts with keys base on array types. The output would be
[{"Asset"=>"Asset", "OtherIncome"=>"Other Income", "OtherExpense" => "Other Expenses"}]
Is it possible without a loop?
Here's a rewrite of your variables with a few changes:
Underscore variable names
valid_account_types is now a hash instead of an array containing a hash.
Some typos corrected so that the members of types match keys of valid_account_types.
valid_account_types = {
'Asset' => 'Asset',
'Liability' => 'Liability',
'Equity' => 'Equity',
'Income' => 'Income',
'CostOfSales' => 'Cost of Sales',
'Expense' => 'Expenses',
'OtherIncome' => 'Other Income',
'OtherExpenses' => 'Other Expenses',
}
types = [
'Asset',
'OtherIncome',
'OtherExpenses',
]
Given that setup, if you are using Rails, you can get the result you want using Hash#slice, like this:
> valid_account_types.slice(*types)
=> {"Asset"=>"Asset", "OtherIncome"=>"Other Income", "OtherExpenses"=>"Other Expenses"}
Note that Hash#slice does not exist in Ruby itself. If you want to do this in plain-old Ruby, you could check out the implementation in i18n:
class Hash
def slice(*keep_keys)
h = self.class.new
keep_keys.each { |key| h[key] = fetch(key) if has_key?(key) }
h
end
end
Your first array isn't an array, it's actually a hash (notice the surrounding braces, rather than brackets):
validAccountTypes = {
'Asset' => 'Asset',
'Liability' => 'Liability',
'Equity' => 'Equity',
'Income' => 'Income',
'CostOfSales' => 'Cost of Sales',
'Expense' => 'Expenses',
'OtherIncome' => 'Other Income',
'OtherExpense' => 'Other Expenses',
}
You can get the keys on the hash and intersect it with your array:
common_keys = validAccountTypes.keys & types
Then you can select only those keys:
# Hash#slice works in Rails:
validAccountTypes.slice(*common_keys)
# Otherwise use Hash#select:
validAccountTypes.select { |key, value| common_keys.include?(key) }
Note that in your example, your hash keys include 'OtherIncome' and 'OtherExpense', but your types array includes 'Other Income' and 'Other Expenses'. Your array values should match the keys from the hash.
I'm trying to get videos from my channel using search function. Response include only nextPageToken, but no prevPageToken. prevPageToken is null always, even if I'm listing other pages using nextPageToken. I use an access_token param from Google Oauth.
My request:
$searchResponse = $youtube->search->listSearch('snippet', array(
'forMine' => 'true',
'order' => 'date',
'pageToken' => $pageToken,
'type'=>'video',
'maxResults' => '10',
'q' => $searchQuery,
));
Result:
Google_Service_YouTube_SearchListResponse Object
(
[collection_key:protected] => items
[etag] => "XXX"
[eventId] =>
[itemsType:protected] => Google_Service_YouTube_SearchResult
[itemsDataType:protected] => array
[kind] => youtube#searchListResponse
[nextPageToken] => Cib3-ZrgSf____9uWHdEYVNIVnlOVQD_Af_-blh3RGFTSFZ5TlUAARAPIbmtEhE6-iWlOQAAAAC2H2UGSAFQAFoLCdIYcGeU2-YsEAJgyOjNygE=
[pageInfoType:protected] => Google_Service_YouTube_PageInfo
[pageInfoDataType:protected] =>
[prevPageToken] =>
[regionCode] =>
[tokenPaginationType:protected] => Google_Service_YouTube_TokenPagination
[tokenPaginationDataType:protected] =>
[visitorId] =>
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
[pageInfo] => Google_Service_YouTube_PageInfo Object
(
[resultsPerPage] => 5
[totalResults] => 55
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
)
Thank you for your ideas!
Petr
UPDATE
This problem is only if is set param forMine. But I need show only my videos...
I have situation like this:
clients = {
"yellow"=>[{"client_id"=>"2178","price" => 1},{"client_id" => "2282","price" => 2}],
"orange"=>[{"client_id"=>"2180","price" => 1},{"client_id" => "2283","price" => 3}],
"red"=>[{"client_id"=>"2178","price" => 1},{"client_id" => "2282","price" => 3}],
"blue"=>[{"client_id"=>"2180","price" => 1},{"client_id" => "2283","price" => 1}]
}
I need to get the key(s) with client ids => [2282,2178] and get the lowest key value based on price.
How can I achieve this?
res = []
client.each{|k, v|
res << k if v.detect{|hash| hash["client_id"] == "2282"}
}
res
#=> ["red", "yellow"]
NOTE
This answer is for OPs original question that required finding keys that contained "client_id" = 2282. I have not updated my answer as OP changed the requirement quite lazily.
In my rails application, I have a button which when clicked, copies data from one database and insert it in another.
I am using octopus gem to link my application to 2 databases.
To copy a record from db_A to db_B, I am using the code below:
Octopus.using(:shard_B) do
#book_new_live = Book.create(
:BK_SUB_FK => #book.BK_SUB_FK,
:BK_TITLE => #book.BK_TITLE,
:BK_SOURCE => "",
:BK_PUB => "",
:BK_COVER => "",
:BK_LABEL_PRODUCT => #book.BK_LABEL_PRODUCT,
:BK_FINAL_LABEL => "",
:BK_VISUAL_METHOD => #book.PRB_VISUAL_METHOD,
:BK_DB => "",
:BK_COVERED_REGION => "",
:BK_VERSION_NO => #book.BK_VERSION_NO,
:BK_SEQ_FILE => "",
)do |primary|
primary.BK_ID = #book.BK_ID
end
end
Database 'db_b', to which data in copied, does not accept null values and the columns cannot be null and the default value is 'NONE'.
Also, I am not allowed to modify the structure of the database so that it can accept null values.
If I use the simplified code below, I get an error message which informs me that the columns 'BK_SOURCE', 'BK_PUB', 'BK_COVER'...cannot be null. By default rails is passing null to those columns.
So I have to pass empty strings to the columns which cannot be null.
Octopus.using(:shard_B) do
#book_new_live = Book.create(
:BK_SUB_FK => #book.BK_SUB_FK,
:BK_TITLE => #book.BK_TITLE,
:BK_LABEL_PRODUCT => #book.BK_LABEL_PRODUCT,
:BK_VISUAL_METHOD => #book.PRB_VISUAL_METHOD,
:BK_VERSION_NO => #book.BK_VERSION_NO,
)do |primary|
primary.BK_ID = #book.BK_ID
end
end
Is there a way of preventing rails from passing null values to the columns not mentioned in the above code?
If i understand you correctly, you can just use the or operator to send your values like this:
Octopus.using(:shard_B) do
#book_new_live = Book.create(
:BK_SUB_FK => #book.BK_SUB_FK,
:BK_TITLE => #book.BK_TITLE,
:BK_SOURCE => #book.BK_SOURCE || "NONE",
:BK_PUB => #book.BK_PUB || "NONE",
:BK_COVER => #book.BK_COVER || "NONE",
:BK_LABEL_PRODUCT => #book.BK_LABEL_PRODUCT,
:BK_FINAL_LABEL => "",
:BK_VISUAL_METHOD => #book.PRB_VISUAL_METHOD,
:BK_DB => "",
:BK_COVERED_REGION => "",
:BK_VERSION_NO => #book.BK_VERSION_NO,
:BK_SEQ_FILE => "",
)do |primary|
primary.BK_ID = #book.BK_ID
end
end
By saying that the value to be passed is #book.BK_SOURCE || "NONE", if the attribute is nil, then the string NONE is passed instead.
EDIT
hash = {
:BK_SUB_FK => #book.BK_SUB_FK,
:BK_TITLE => #book.BK_TITLE,
:BK_SOURCE => #book.BK_SOURCE,
:BK_PUB => #book.BK_PUB,
:BK_COVER => #book.BK_COVER,
:BK_LABEL_PRODUCT => #book.BK_LABEL_PRODUCT,
:BK_FINAL_LABEL => #book.BK_FINAL_LABEL,
:BK_VISUAL_METHOD => #book.PRB_VISUAL_METHOD,
:BK_DB => #book.BK_DB,
:BK_VERSION_NO => #book.BK_VERSION_NO
}
hash = hash.delete_if { |k, v| v.nil? }
Octopus.using(:shard_B) do
#book_new_live = Book.create(hash)do |primary|
primary.BK_ID = #book.BK_ID
end
end
Give it a try.
I now, that question could be non good for so, but need help:
In my rails haml view i have such code:
%table.table.table-striped
= form_tag :admin_other_price_upload do
%tr
- #csv.first.length.times do |n|
%th
= n + 1
%br/
=select_tag "s"+(n+1).to_s, options_for_select([["Брэнд", "Brand"], ["Артикул","Article"], ["Наименование","Descr"], ["Цена","Price"], ["Количество","Quantity"], ["Дополнительно","Other"], ["Поле кроссов","Cross"]]), :prompt => 'Все', :id => "select-value"
*********************************
so as you can see i'm setting to all select's name like s(n+1) and value one from list. But how can i get them both in controller method? I need it becouse i have dynamic table. I will explain it on example:
So i have table with select's
name = s1 (value = Brand) | name = s2 (value = Price)
so i need in controller to get not only that s1 => Brand, but also get this 1 from s1
So if param look's like
[
s1 => {Brand}
]
I need to get for my calculation s1 not value, but s1 as string (simple i need to find in params, which value has Brand and select it as a value)
So for Brand i need to select s1, and set as s1 value s1, how could i do it?
I may have understood you, but not sure.
# let's say your params hash is like:
params = { :action => 'show', :controller => 'articles',
:s1 => 'Article', :s2 => 'Brand', :s3 => 'Price', ... }
brand_param = params.select{ |key, value| value == 'Brand' }
# => { :s2 => 'Brand' }
which_s_is_brand = brand_param.keys.first.to_s
# => 's2'