Pass values of checkboxes into an array? - ruby-on-rails

Im trying to update someone else's Rails app. Right now, an HTML table displays values from a database. What i want is to be able to display a checkbox for each row and on submit, the values of the checkboxes are sent into an array (and the values shouldnt be "checked" or "unchecked", they should be the id's of the database row).
Heres what i have so far.
Checkbox : (message.id being a dynamic id)
<%= check_box_tag "message_ids[]", message.id %>
And on the controller:
#dispatches = Dispatch.find_by_message_ids(CODE TO RETRIEVE CHECKBOX ARRAY GOES HERE)
Any suggestions?

Have you tried inspecting the value of params?
Chances are this will work:
#dispatches = Dispatch.find_by_message_ids(params[:message_ids])
But if it doesn't, just look at what is being sent to your page. Try one of these:
logger.info(params)
or
raise (params.inspect)
or
render :inline => params.to_yaml

Check what you receive in your params because they're probably there if this is defined correctly. The current parameters are always logged in log/development.log which is something you should have open any time you're debugging something.

Related

Rails / design array issue

In my 'releases' show view I have the following code:
<% i = #release.id %>
<%= link_to image_tag('next.png'), release_path(i+1), :class => "editRelease" %>
Which takes the user to the next result in the releases table.
I am hoping to only display this 'next' button if an item exists in the array whose id value is one greater than the current release.
Happy to re-write this section of the view / place code in model,controller,helper definition.
Just trying to learn the correct rails way to solve this issue!
Thank you!
Records can be deleted, leaving gaps in your range of ID's, as such using a direct id+1 could point to a null record.
Instead you should define a next method in your model that safely returns the next object. If you don't have any ordering then you can use a query like the one posted in this answer.

Rails - Efficient way of finding entries with specific value in model

So I am trying to find all entries in my table that have a specific value in a particular column. The only way I can think off to do this is to look at each entry and see if it has the value but I was hoping there would be a more efficient solution - this gets unwieldy once you have a sizable database.
Does anyone have a better idea?
Update - I am creating an HTML table and I want to populate the table with all the entries in my model that have a certain value in a particular column. I am trying to do:
<%= render #users.where("column_name = 'value'") %>
as the answer below recommends but I get "undefined method `where' for nil:NilClass" error.
Update 2 - I am not sure why #users would be nil but I will try to figure that out later. For now, I tried
<% #user_message = User.where("column_name = 'value'") %>
<%= render #user_message %>
but it doesn't show any entries at all.
Update 3 - When I do, User.all in rails console, I get all the users so I know the data is there. However, when I do User.where("column_name = 'value'"), I get an empty array. I double checked the column name and value to make sure that the data was present.
Update 4 - Fixed! - I'm not sure why it didn't work in rails console but I got it to work in the site. I called my partial _user_message.html.erb. Apparently it still needs to be called _user.html.erb. Thanks for the help everyone!
Sounds like you want to do a where query, i.e.
#records = Model.where(:some_column => some_value)
Rails has excellent documentation, I suggest you take a look at the ActiveRecord Query guide:
http://guides.rubyonrails.org/active_record_querying.html
ian.

Ruby on Rails - passing hashes

I have a piece of controller code where some values are calculated. The result is in the form of an array of hashes. This needs to get into a partial form somehow so that it may be retrieved later during commit (which is through the Submit button).
The questions is how do we pass the array of hashes?
thanks.
Is there a reason it has to be through the form? This is the type of thing I usually use the session for.
I can't really think of a nice way to do what you're asking with forms. I guess you could create hidden fields for each key in your hash in the form with hidden_field_tag as an alternative. Then you run into problems translating it (what if a key's value is an array or another hash?).
You could easily store the hash in the session and then on each page load, check to see if there is a hash where you expect it. On calculating values:
session[:expected_info] = results
And each page load, something like this:
if session.has_key?(:expected_info)
results = session.delete(:expected_info)
# you already calculated the results, just grab them and
# do what you need to do
else
# you don't have the expected info
end
You should be able to pass it as a string to your partial:
[{}].inspect
and eval it when it is submitted back through the form:
eval("[{}]"))
but that would be really dirty…

Rails: Flatten array in parameter

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.

rails accessing value from facebooker hash/array

This is my first time using the facebooker plugin with rails, and I'm having trouble accessing user info. The website uses FB connect to authenticate users.
I am trying to get the name of the university that the logged in user attends.
When I use the command <%= facebook_session.user.education_history[:name] %>, I get an error "Symbol as array index".
I have also tried using education_history[1], but that just returns
"# Facebooker::EducationInfo:<some sort of alphanumeric hash value>"
When I use something like <%= facebook_session.user.relationship_status %> , it returns the relationship status just fine.
Similarly,
<%= facebook_session.user.hometown_location.city %> returns the city name just fine.
I've checked out the documentation for facebooker, but I can't figure out the correct way to get the values I need.
Any idea on how to get this to work?
Thanks!
facebook_session.user.education_history returns an array of Facebooker::EducationInfo objects. The proper way to access it would be:
ed = facebook_session.user.education_history.last #Will be nil if not provided
#ed_name = ed.name unless ed.nil?
I am not sure the order they are sorted in, so you may need to call .first instead of .last

Resources