Rails: Flatten array in parameter - ruby-on-rails

I'm trying to flatten an array for my form.
def update
#tour = Tour.find(params[:id])
params[:tour][:hotel_ids][0] = params[:tour][:hotel_ids][0].split(',')
...
This results in:
"hotel_ids"=>[["1","2"]]
Naturally I want it to be
"hotel_ids"=>["1","2"]
My Form:
<%= text_field_tag 'tour[hotel_ids][]', nil %>
Hope anyone can help with this.
EDIT
I've gotten it to work, somehow. This might be a bad way to do it though:
I changed the text_field that get's the array from jquery to:
<%= text_field_tag 'tour[h_ids][]', nil %>
then in my controller I did:
params[:tour][:hotel_ids] = params[:tour][:h_ids][0].split(',')
And this works, I had to add h_ids to attr_accessor though. And it will probably be a big WTF for anyone reading the coder later... but is this acceptable?

This is ruby!
params[:tour][:hotel_ids][0].flatten!
should do the trick!
ps: the '!' is important here, as it causes the 'flatten' to be saved to the calling object.
pps: for those ruby-related questions I strongly suggest experimenting with the irb or script/console. You can take your object and ask for
object.inspect
object.methods
object.class
This is really useful when debugging and discovering what ruby can do for you.

Simply use <%= text_field_tag 'tour[hotel_ids]', nil %> here, and then split like you do in example.
What really happens in your example is that Rails get param(-s) tour[hotel_ids][] in request and it thinks: "ok, so params[:tour][:hotel_ids] is an array, so I'll just push every value with this name as next values to this array", and you get exactly this behavior, you have one element in params[:tour][:hotel_ids] array, which is your value ("1,2"). If you don't need (or don't want) to assign multiple values to same param then don't create array (don't add [] at the end of the name)
Edit:
You can also go easy way (if you only want answer to posted question, not solution to problem why you have now what you expect) and just change your line in controller to:
params[:tour][:hotel_ids] = params[:tour][:hotel_ids][0].split(',')
#split returns array and in your example you assigned this new array to first position of another array. That's why you had array-in-array.

Related

each_with_index not working for an array rails [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
When each_with_index is used along with an array of active records returned from a query and when i call the attributes of the model. it says undefined method, for the attribute
Controller
#user_contact_query=Usercontact.select("*")
#available_contacts_array=Array.new
#user_contact_query.each do |variable|
#user_query=User.find( :all,:conditions => ["id = ?",variable.relator_id])
#available_contacts_array.push(#user_query)
end
View
<% #available_contacts_array.each_with_index do |variable, index| %>
<%= variable.email %>
<% end %>
Well, step by step, since this is rather bad code:
#user_contact_query = Usercontact.select("*")
the select part here is a bit strange, I would have used .all. Otherwise no problem here.
#available_contacts_array = Array.new
since in the next line you assign an array anyway there is no need to 'initialize' this variable here, you could just omit that line. (Most Ruby programmers would use [] to initialize an empty array in most cases)
#available_contacts_array = #user_contact_query.to_a
Assuming that we get some records back from the query we now should have an array with user contact objects. Again a simple .all would have had a similar effect as far as I understand what's going on. But assuming that Usercontact has email this is fine and what you expect it to be.
#user_contact_query.each do |variable|
#user_query = User.find(:all, :conditions => ["id = ?", variable.relator_id])
#available_contacts_array.push(#user_query)
end
Now if I get this right what you do is you go through all Usercontacts you found, find every User related to it (possibly more than one) and then attach the result at the end of the array of Usercontacts. As a result you have a mix of Users and Usercontacts in that array. (Which still would work in your view if both have email, since thanks to duck typing Ruby would not care. But most likely one of both is missing email). Also if more than one User is found then an array of users is pushed. And an array for sure has no email.
Ok, with your edit it becomes simple. When you use :all with find then what you get is not a record but an array of records (even if there us only one.). You can just do:
User.find(variable.relator_id)
which will then find a single record and push that in the array. Which I guess is what you expect it to do.
There would be better ways in Rails to do this but this would require the models to be defined properly what your use of relator_id makes look unlikely.
First off please post your full error message. Although Without seeing the error I can tell with certainty that the issue is caused by you calling a method on a nil object i.e you think a value exists where it actually does not.
Besides that you really really should take more care of your code. The code you have right now is just plain horrible. This is an equivalent of your code:
#available = []
UserContact.find_each do |contact|
#available << User.find(contact.relator_id)
end
An alternative is to use #inject
#available = UserContact.all.inject([]) do |list, contact|
list << User.find(contact.relator_id)
list
end
And the best solution would be to actually use ActiveRecord assocations here.
P.S your code does not make much sense anyhow. Why would you put users contacts and users both into that list?
Why don't you do just?
controller's helper:
#array = Usercontact.select( "*" ).map do| variable |
User.find( :all,:conditions => [ "id = ?",variable.relator_id ])
end
view's helper:
#array.each.with_index do| variable, index |
# ...
end
General note: you'be used in the #available_contacts_array variable mixed types, probably this lead to the error, please don't do in such matter.

Display all versions of individual records in Papertrail

I'm building a league system and currently it stores and updates the players 'elo score' depending on the result. Now, I'm trying to add in 'HighCharts' to display the players elo score over the season in a sweet looking line chart. Someone suggested I use Papertrail to store the updates and I have got that all installed.
Now here comes my problem, I can't seem to figure out how to spit out the users elo_score versions in an array easy for 'HighCharts' to use. I can get the last updates to elo_score:
Last updated score = <%= #player.versions.last.reify.elo_score %>
But I can't seem to find the syntax to spit out all the 'versions' for 'elo_score'. Something like "1000, 1020, 1043, 1020".
I've also tried:
<%= #player.versions.map { |version| version.reify.elo_score} %>
But this gives me "undefined method `elo_score' for nil:NilClass". While just <%= #player.versions.map { |version| version.reify %> spits out all information in the record and obviously not just the elo_score.
Can anyone help? Sorry if I've not made this clear, I'm absolute brand new to rails, and this is just a fun project in my spare time but I'm having a blast!
Thanks alot!
What you did here:
#player.versions.map { |version| version.reify.elo_score }
Is perfectly fine to take all those scores and put them in an array. The problem that you're getting (the nil:NilClass stuff) is coming because at least one reify is nil. That is, that some version doesn't have a reify.
If each version is supposed to have a reify, be sure to add that as a model validation, and find in your code where the reify is being set and see why it's nil.
If it's okay for a version to have a nil reify, you could accomplish it a number of ways, but the straightforward and explicit way would look like this:
elo_scores = []
#player.versions.each do |version|
unless version.reify.nil?
elo_scores << version.reify.elo_score
end
end
I would suggest putting this in to a method, like get_elo_scores, and then you could more easily call it like:
#player.get_elo_scores
EDIT For clarification from the comments:
Your User model (or Player model, whatever you named it) should have a method that looks like this:
def get_elo_scores
elo_scores = []
self.versions.each do |version|
unless version.reify.nil?
elo_scores << version.reify.elo_score
end
end
return elo_scores
end
I apologize for not making this clearer, but you won't have access to #player within this method because that only exists in the context of your controller and view. The above is now a proper instance method: it will call .versions upon itself, and the rest is fine. I also added an explicit return call at the end.
Now you will be able to call #player.get_elo_scores on any User (or Player) object.
Hope that helps!
Here's a one-liner version of #MrDanA's answer :
elo_scores = self.versions.map{|version| version.reify.elo_scores}
note that you can't check if version.reify.nil? though

When using a date, what can I do with a nil value?

So I've got an object in my database with a date field, except sometimes it will be nil. Is there a way in the view I can show this as a string value. Something like TBA maybe?
<%= #event.date || "TBA" %> should do it.
In response to your comments, yes, you could do this in the model but it's a bad idea. Why?
First of all, it is about presentation of the data so for that reason it belongs in the view.
Secondly, it could break things. If you did it in the model, #event.date would sometimes return a date and sometimes a string. What would happen if you called #event.date.hour and date was "TBA"? You'd get an error. The only fix would be to check for it everywhere, which would be horrible.
If you really are going to be doing it a lot you could create a helper method in application_helper.rb that could look something like this:
def date_or_tba(date)
date || "TBA"
end
So you could then write in your view:
<%= date_or_tba #event.date %>
Which isn't much less typing but would have the not inconsiderable advantage of restricting the use of the string "TBA" to only one place - which means if you ever need to change it (for I18n purposes for example) - it's really easy.

Why do I get nil objects iterating an array in an ERB template?

I am new to Ruby and currently trying a few experiments.
I am confused about these scripts:
<%=#myworlds[2].topic%>
and
<% id = 1 %>
<%=#myworlds[id+1].topic%>
#mywodrld is an instance of a model and topic is the field. When executing the first one, the program runs correctly. When I run the second script, I get the following error:
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.topic
What causes the nil object?
When I try your approach, I can't replicate your problem. It works fine for me. My guess is that you might use the variable id somewhere else also and that when you call #myworlds[id+1].topic id has some other value. But as I said, only a guess.
However, I recommend that you use another syntax when looping through collections of models in Ruby. Try something like this:
<% #myworlds.each do |myworld| %>
<h1><%= myworld.topic %></h1>
<% end %>
And if you really need the value of the iterator, you could always go with:
<% #myworlds.each_with_index do|myworld, i| %>
Where i keeps track of the current index in the array. Another good thing with this is that id no longer exists in memory after the block ended.
Are you sure that you have no other differences between these two code snippets?
In your comment you say that you have #myworlds[#id+1], in the original question you say #myworlds[id+1] (local variable versus instance variable). Can you show the exact code?
Both scripts are OK. You can create variables in one <% %> block, and you can use them in another one (if they are in the same .erb file, of course).
The error message says that your array has no element with index #id+1 or id+1. You have to debug the value of the expression used for the index. I guess that there is somewhere some small mistake, like a typo.
What is the output of your debug(#myworlds[#id+1]) statement when #myworlds[#id+1].topic raises the error?
Also try to debug the value of id:
<pre>The id = <%= debug(id) %> (<%= id.inspect %>)</pre>
(Depending on your version of Rails you may want to use h( id.inspect ))
I'm guessing but for some reason id+1 is probably not equal to 2.
To check the value of id+1 you can do that :
raise (id+1).inspect
Inspect is very useful is you want to see what is in an object :)
I think I know how to solve the problem is. You are trying to each an array data from a model, but u use the parameter [#id+1]. No matter the "id" is global or local variable, but the problem is in the end of array, there are no array with index "id+1". You should add another parameter to prevent the unrecognized parameter.
Try this
if((#myworlds.length-1) > #id)
#id = #id+1
end
:D
It looks like you're looping over an array, but possibly using a for or while loop to accomplish it, rather than use an [].each. Your sample code doesn't give us enough information to work from so we're shooting in the dark attempting to help you.
Manually creating your index then trying to walk the array tends to run into problems where you either miss the first or last item, or you go too far and get the error you are seeing. Because each returns only the items in the array it can't do that.
Something like this might work better:
<% #myworlds.each do |world| %>
...
<%= world.topic %>
<% end %>
I didn't see the answer #DanneManne gave before I wrote my response. I think he's got the right solution.

rails if object.nil? then magic '' in views?

This is one of those things, that maybe so simple I'll never find it because everyone else already knows it.
I've got objects I have to check for nil in my views so I don't dereference a nil:
<%= if tax_payment.user; tax_payment.user.name; end %>
Or I could do this variant:
<%= tax_payment.user ? tax_payment.user.name : '' %>
So this is ok ... for most languages. But I feel like there must be some bit of shiny ruby or railness I'm still missing if this is the best I can do.
What about:
<%= tax_payment.user.name if tax_payment.user %>
You can also try the new Object.try syntax, pardon the pun.
This is in the shiny new Rails 2.3:
tax_payment.try(:user).try(:name)
The Ruby community has put an incredible amount of attention to automating this idiom. These are the solutions I know of:
try in Ruby on Rails
Another try
andand
A safer andand
Kernel::ergo
send-with-default
maybe
_?
if-not-nil
turtles!
method_ in Groovy style
do-or-do-not
The most well-known is probably the try method in Rails. However, it has received some criticism.
In any case, I think Ben's solution is perfectly sufficient.
I've always preferred this approach:
model:
class TaxPayment < ActiveRecord::Base
belongs_to :user
delegate :name, :to=>:user, :prefix=>true, :allow_nil=>true
end
view:
<%= tax_payment.user_name %>
http://apidock.com/rails/Module/delegate
For a little more comprehensive solution, you could check out the Introduce Null Object Refactoring. The basic mechanics of this refactoring is that instead of checking for nil in the client code you instead make sure that the provider never produces a nil in the first place, by introducing a context-specific null object and returning that.
So, return an empty string, an empty array, an empty hash or a special empty customer or empty user or something instead of just nil and then you will never need to check for nil in the first place.
So, in your case you would have something like
class NullUser < User
def name
return ''
end
end
However, in Ruby there is actually another, quite elegant, way of implementing the Introduce Null Object Refactoring: you don't actually need to introduce a Null Object, because nil is already an object! So, you could monkey-patch nil to behave as a NullUser – however, all the usual warnings and pitfalls regarding monkey-patching apply even more strongly in this case, since making nil silently swallow NoMethodErrors or something like that can totally mess up your debugging experience and make it really hard to track down cases where there is a nil that shouldn't be there (as opposed to a nil that serves as a Null Object).
I just do
<%= tax_payment.user.name rescue '' %>
Another option, which makes sense occasionally...
If tax_payment.user returns nil, nil.to_s (an empty string) is printed, which is harmless. If there is a user, it will print the user's name.
You could write a helper method which looks like this:
def print_if_present(var)
var ? var : ""
end
And then use it like this (in the view):
<%= print_if_present(your_var) %>
If the var is nil, it just prints nothing without raising an exception.

Resources