Mapping data into correct format Ruby on rails - ruby-on-rails

This should be an easy one but I am not getting it right. Looked around on Google and SO and found a few suggestions but can't get any of them to work for me.
I need to output a specific data structure which is an array of hashes that contains an index for each hash:
[ id => {:key=>"foo", :value=>"bar"}]
I have a Class object ("Foo"), that I need to map into the above structure. I have come this far:
[{:key=>"personal", :value=>"age"}]
...Using this Code:
check = Foo.find(1)
check.collect{|r| {:key => r.name, :value => r.type}}
What I'd like to achieve is to add an index to the hash above. The index's value should be "check.id".
I think that this might be heading in the right direction but not sure (Results in an error):
check.group_by {|r| r.id }.collect{ |r| {:key => r.name, :value => r.type}}

This should work
check.collect{|r| {r.id.to_s => {:key => r.name, :value => r.type}}}
Actually I assume you want to get hash of hashes:
Hash[ *check.collect { |r| [r.id.to_s, {:key => r.name, :value => r.type}] }.flatten ]

Related

Access params with wildcard in Rails

At the moment I have a form_tag which contains inputs and puts these inputs into parameters.
I want to be able to loop over them in the controller action.
I've tried getting all params excluding all the usual params (action, controller, model name etc.) and then using a wildcard like params[:prop*].
Here is the offending form inputs:
%input{:name => "userEmails", :id =>"userEmails", :type => "hidden", :value => ""}
-#all_properties.each do |prop|
%input{:name => "prop"+prop.name+"checkbox", :type => "checkbox", :id => "prop"+prop.name+"checkbox"}
#{prop.name}
%input{:name => "prop"+prop.name, :type => "text", :id => "prop"+prop.name}
These show up in params like {"propProperty1checkbox"=>"on", "propProperty1" => "testing", "propAnotherPropertycheckbox" => "on", "propAnotherProperty" => "another test value"} etc.
I'm unsure how to access these as the names of the properties can change and so need to be accessed abstractly.
You can use #select on params hash to filter only the params that are interesting for you:
params = {"user_id"=>1,
"propProperty1checkbox"=>"on",
"propProperty1"=>"testing",
"propAnotherPropertycheckbox"=>"on",
"propAnotherProperty"=>"another test value"
}
params.to_h.select{|key, value| key =~ /^prop/}
#=> {"propProperty1checkbox"=>"on",
#"propProperty1"=>"testing",
#"propAnotherPropertycheckbox"=>"on",
#"propAnotherProperty"=>"another test value"}
EDIT
Example from the comment:
[13] pry(main)> {"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"xxxxx", "userEmails"=>"teste#test.com,test2#test.com,test4#test.com,fasd#gmail.com", "propProperty1checkbox"=>"on", "propProperty1"=>"3", "propAnotherPropertycheckbox"=>"on", "propAnotherProperty"=>"4", "commit"=>"Submit", "Application"=>"8", "Company"=>"1" }.to_h.select{|k, v| k =~ /^prop/}
=> {"propProperty1checkbox"=>"on",
"propProperty1"=>"3",
"propAnotherPropertycheckbox"=>"on",
"propAnotherProperty"=>"4"}
You can try something like:
input(name: "props[#{pro_name}][checkbox]"...)
input(name: "props[#{pro_name}][text]"...)
Then, in your controller:
def method
props = params[:props]
props.each do |property_name, values|
chk = values[:checkbox]
text = values[:text]
end
end

Searching with multiple conditions (Ruby on Rails)

I want to search a table with multiple conditions in Rails.
I am working on deleting certain package(record) from database but first i need to get userId and packageID .
and here is the code i wrote but it gives error.
#package=Packages.find(:all, :condition => {:id => params[:pid]}, :condition => {:senders_id => cookies[ :user_id ]})
here is the error :
ArgumentError in CreatePackagesController#deletepackage
Unknown key: condition
i just need equivalent code with the right syntax to that one if someone could help.
def deletepackage
#package=Packages.find(:all, :conditions => {:id => params[:pid], :senders_id => cookies[ :user_id ]}
if (#package!=nil && req.receivedByCarrier==false)
#package.destroy
elsif (#package!=nil && req.receivedByCarrier==true)
#package.destroy
end
return;
end
Change your query as below:
#package = Packages.find(:all, :conditions => {:id => params[:pid], :senders_id => cookies[:user_id]})
You are getting the error as Unknown key: condition because :condition is not a valid option in find method.
:condition should be :conditions (Note plural). Also, you should be passing both the conditions as a single key-value pair.
For Rails 4.x
You can simply do it as below
#package = Packages.where(id: params[:pid], senders_id: cookies[:user_id])
This
#package=Packages.find(:all, :condition => {:id => params[:pid]}, :condition => {:senders_id => cookies[ :user_id ]})
should be like this
#package=Packages.find(:all, :conditions => {:id => params[:pid]}, :senders_id => cookies[ :user_id ]})

Search by ID, no keyword. Tried using :conditions but no result ouput

Using Thinking Sphinx, Rails 2.3.8.
I don't have a keyword to search, but I wanna search by shop_id which is indexed. Here's my code:
#country = Country.search '', {
:with => {:shop_id => params[:shop_id]},
:group_by => 'state_id',
:group_function => :attr,
:page => params[:page]
}
The one above works. But I thought the '' is rather redundant. So I replaced it with :conditions resulting as:
#country = Country.search :conditions => {
:with => {:shop_id => params[:shop_id]},
:group_by => 'state_id',
:group_function => :attr,
:page => params[:page]
}
But then it gives 0 result. What is the correct code?
Thanks.
Have a go in the console and see if you cant shift the :conditions around. It looks like by removing the blank string you simply have set a default param for the gem. Get the Gem in your Vendor and have a look at the Country Class to see what is accepts.

Is it possible to know when an associated object is about to be destroyed?

When you have a one-to-many association in Rails 3 and accept nested attributes with delete, is it possible to know by looking at the objects (the associated object) whether it's going to be deleted or not?
For example:
group.attributes = {:member_attributes => {"0" => {:id => 1, :name => "John"},
"1" => {:id => 2, :name => "Dave"},
"2" => {:id => 3, :name => "Gus", "_destroy" => true}}}
Is it possible by looking at group.members to know that the one with id 3 is going to be deleted on save?
There's a method for finding that out, called marked_for_destruction?
group.members.each do |member|
puts "#{member.name} => #{member.marked_for_destruction?}"
end
would generate
John false
Dave false
Gus true

Rails -- Find condition with id's all over the place

I have this find condition pulling from my model that currently looks like this.
#major_set = Interest.find(:all, :conditions => {:id => 1..21})
I'd like to add some more individual ids that I've just added which are like 120...130. I tried to do...
#major_set = Interest.find(:all, :conditions => {:id => 1..21, 120..130})
but got the error. " syntax error, unexpected '}', expecting tASSOC ...ns => {:id => 1..21, 122..130})"
How can I select multiple sets of id's as well as maybe some individual ids, ie ( :conditions => {:id => 1..21, 121..140, 144, 155 }??
You can convert the ranges to arrays and add them together. E.g.
#major_set = Interest.find(:all,
:conditions => {:id => (1..21).to_a + (120..130).to_a})
If you then want to add in individual ids then you can just add them to the array. E.g.
ids_to_find = (1..21).to_a + (120..140).to_a
ids_to_find << 144
ids_to_find << 145
#major_set = Interest.find(:all, :conditions => { :id => ids_to_find })
If you type {:id => 1..21, 122..130} inside irb you will get an error because it is not valid ruby syntax. This is interpreted as a hash where the first element is :id => 1..21 and the second is missing its key.
In order to make it a valid ruby expression, you would need to type:
{:id=>[1..21, 122..130]}
But I don't think that ActiveRecord will accept that syntax. So you may need to:
:conditions => "id BETWEEN 1 AND 21 OR id BETWEEN 122 AND 130"
This works in MySQL. I don't know if it will work in other databases.

Resources