I have a Rails app where I list records on an index page.
One of the columns is:
<td><%= check_box_tag "event_ids[]", event.id %></td>
I have a button on the bottom of the index page:
<%= link_to 'Submit ', addinvtimes_invtimes_path, :class => 'btn btn-success' %>
I wanted this code to run in the invtimes controller:
def addinvtimes
if params[:event_ids] != nil
params[:event_ids].each do |i|
newinvtime = Invtime.new(
linetype_id: 1,
invoice_id: #invoice.id,
event_id: i.to_i
)
end
end
end
But, params[:event_ids] is nil even if several boxes are checked.
Can't you submit params using an index page? Does it have to be a form?
Thanks for the help!
UPDATE 1
I tried passing the array event_ids[] in the call:
<%= link_to 'Submit ', addinvtimes_invtimes_path(:workorder_id => #workorder, :event_ids[] => event_ids[]), :class => 'btn btn-success' %>
But, got:
wrong number of arguments (0 for 1..2)
I just need the array event_ids[] to be accessible in the controller code addinvtimes.
UPDATE2
All I'm trying to do is list a bunch of records and include a checkbox column. Then in the controller get back a list of ids for the rows that were checked.
The type of the page (index, new, edit, etc.) does not affect the ability to submit data, however, a form is required if you want to post data using pure HTML to be in the params hash.
UPDATE1:
As for the update, adding :event_ids[] as a parameter to the link will only add it as a querystring parameter to the link, assigning it the value of event_ids[] at the time the view is parsed. Changes to the checkboxes in the html will not be reflected in the querystring. I think, the easiest way would be to just wrap the checkboxes and the submit into a form tag and let it post the data to your controller action.
Oh, and I just saw, the wrong number of arguments error resulted in calling [] on event_ids without an index. I wasn't sure, but apparently you can't have [] in variable names.
Related
I did the following to be able to search through unique attributes (removing duplicates) with a select dropdown.
The issue is that when submitting a search after an initial search, it breaks.
View:
<%= form_tag vendor_orders_path, :method => 'get' do %>
<%= collection_select(:search, params[:search], #vendor_line_items, :store_title, :store_title, {}, {class: "form-control-sm col-5"})%>
<%= submit_tag "Search", :name => nil, class: "btn btn-primary btn-sm" %>
Model:
def self.line_item_search(search)
scope = joins(:line_items)
line_items = scope.where(line_items: { id: LineItem.where(store_title: "#{search.join(', ')}") })
line_items
end
Note: .join(', ') This allows me to search through the Array parameter.
Controller:
if params[:search]
#orders = Order.line_item_search(params[:search]).joins(:line_items).where(line_items: {vendor_id: #vendor.id})
end
Errors:
This all works on the first search. But when I search twice (after a successful search), it breaks with the following params and errors:
Parameters: {"utf8"=>"✓", "search"=>{"\"Copy of Copy of t-shirt 123\""=>"Copy of Copy of t-shirt 123"}}
NoMethodError (undefined method `join' for #<ActionController::Parameters:0x00007f45a47f9428>):
It is stating the error is in line 73 in the controller which is:
#orders = Order.line_item_search(params[:search]).joins(:line_items).where(line_items: {vendor_id: #vendor.id})
Questions and possible alternatives:
How can I clear the previous search in the url?
Is there a better way to go about getting the unique attributes from the LineItem model? In the past, when using search forms, I never had this issue when it was just using a string or an integer. I assume clearing the search results isn't the best solution as much as just getting a list of strings to not need to use .join(', ') to get the search results.
What are your thoughts
I think your issue is with your form. Why are you feeding in a second argument of params[:search] into collection_select?
See https://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select for which arguments you need and where
Using:
<%= select_tag :search, options_from_collection_for_select(#vendor_line_items, :store_title, :store_title, params[:search]), class: "form-control-sm col-5" %>
Instead of collection_select solved all issues. It turned the select into a string, without the need of using .join(', ') in the model. And it allowed searching after a search
I have a form tag which acts as a search form.
I have a set of locations - params: name and id, which Im displaying as collection boxes in the form tag. The search tag displays people for each location who can then be added to the project. By choosing a location on the form tag, you can filter down people for just that particular location.
The search form works fine and Correctly gives me people at each location
Here is what is in the view
<%= collection_check_boxes(#locations, :location_ids, #locations.all, :id, :name) %><br>
Here is the form tag it's enclosed in:
<%= form_tag interviewers_tenant_project_path(#project, tenant_id: #tenant.id), method: :get do %>
Locations are project specific, and I'm creating an instance variable to return all the locations valid for a project.
My problem is that after the form returns the data, the previously selected location check box is not ticked.
Here is my code in the controller
#locations = Location.where("name in (?)", project_locations)
#locations.each do |loc|
puts "loc.name #{loc.name}, #{loc.id}"
def loc.location_ids
[1]
end
end
def #locations.location_ids
puts "ENTER #locations.location_ids "
#location_values
[1]
end
the documentation says this:
collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
"Returns check box tags for the collection of existing return values of method for object's class. The value returned from calling method on the instance object will be selected. If calling method returns nil, no selection is made."
So I've tried adding a method to the object (singleton method) and then when that didn't work, I tried adding a method to each active record instance.
I have hardcoded the value [1] - which corresponds to the first location in my database. But I just cannot make the checkbox selected when the form is re-rendered after the search.
Im new to rails - about 2 months into my project - before that a month studying RoR, so all insights would be beneficial.
Thanks for your help and time
I worked around this finally. I didn't want to re-write the controller. So I tried adjusting the names of the check boxes to the same names as those generated by the collection tag. I have also put 3 extra lines of code, starting with <% param ... which helped me debug the right value. I guess rails experts would call it an ugly hack ... ? Anyways, the check boxes work fine and I didnt have to touch the controller code.
<% #locations.each do |loc| %>
<%= params.has_key?(:location) %>
<%= params.has_key?(:location) && params[:location].has_key?(:location_ids) ? params[:location][:location_ids].to_s : "empty" %>
<%= params.has_key?(:location) && params[:location].has_key?(:location_ids) && params[:location][:location_ids].include?(loc.id) %>
<%= check_box_tag("location[location_ids][]" , loc.id, params.has_key?(:location) && params[:location].has_key?(:location_ids) && params[:location][:location_ids].include?(loc.id.to_s) ? loc.id : nil, id: "location_" + loc.id.to_s) %>
<%= label_tag("location_" + loc.id.to_s, loc.name) %>
<% end %>
I met a problem of parameter passing in Rails.
I have an object named 'account' and another object named 'locale'. There is a one-to-many relationship between them. One locale can be mapped with multiple accounts.
On accounts/index.html.erb, I have a dropdown which will list all the available locales.
And I have a link below.
In expectation, when I clicks this link, the index method of account controller will be called and the value of selected locale id will be passed. And the index method will retrieve all the accounts belonging to that locale.
What blocks me is I have no idea how to pass that selected value of dropdown to the controller.
I only know the basic way of passing a parameter is:
<%= link_to 'Refresh', {:action => 'index', :fromvar => 'refresh', :selected_locale_id => '1'}.
And from controller, we can get it by:
params[:selected_locale_id]
But it is the case of a fixed value. How to deal with a dynamic UI control value as my case?
Does link_to support some javascript to be embedded?
My rails version is 3.2.13.
Any one has idea on this?
You can either do this as a form, or as javascript in the onclick event of the link. I would recommend a form.
The following should get you started:
<%= form_for :index do |form| %>
<%= form.select :locale_id, Locale.all %>
<%= form.submit %>
<% end %>
Be sure to add a post route to the index action to allow the form to submit.
I'm a RoR beginner and am using Rails 3.2.3.
I have a search form on my page and it performs a get request and filters the results correctly.
I want to add the possibility of also searching Products by dates.
I inserted a date_select and am able select the date and when the page refreshes after the search, the chosen dates are still there on the date_select, as I am able to get them through params.
However, my issue is that when the page renders the products, they have a link_to to their show action.
My goal is to also pass alongside the url the dates that were selected to perform the search on that link_to.
For ex, if the user selects a date of 20-06-2012 to 25-06-2012 it only shows products inserted on that time frame (and all those params are on the url)
But the link to show action of each displayed product is only:
link_to <%= link_to product.name, product%>
which renders
http://localhost:3000/products/24 (por example)
what I want to render/show is something like:
http://localhost:3000/products/24?from=20-06-2012&to=25-06-2012
The selected dates to perform the search are not stored in the database at this moment, but I will need to get them from the URL on a latter page, therefore, both dates will need to be preserved through 2 different pages before the users fills a form and then those dates are inserted in the DB.
Any tips on this? I've searched but all I found was on how to pass variables that exist in the model and I do not want to use cookies nor session variables.
Thanks in advance,
Regards
If you want to pass arbitrary parameters to the following call
<%= link_to product.name, product %>
you need to invoke the path method explicitly instead of using the implicit version. The line above is equivalent to
<%= link_to product.name, product_path(product) %>
Then you can pass parameters
<%= link_to product.name, product_path(product, :from => 'whatever', :to => 'whatever') %>
Can you try like this
link_to <%= link_to product.name, product, :param_you_want => "value you want" %>
Now you can set value in "param_you_want" as you wish.
But in my case set value in it "value you want"
Hope you can get idea
I'm new to Rails so be gentle. I've got a model, 'Event', with the the following information: 'sport', 'home_team', 'away_team', and 'time' in datetime.
Now I want to enable the user to 'follow' a specific event and am trying to find the best way to do so. Ideally, I'd like a form with dependent drop down lists. For example, the user first picks a 'day', then a 'sport', then selects from a relevant list of 'events' of that 'day' and 'sport'. This association is then stored in a rich join table called 'following'.
I've seen tutorials on complex forms that involve multiple models, but what about when everything is from the same model? How do build a form to grab a handful of relevant records. I only have a few distinct values for 'sport', so I wasn't sure it made sense to give it its own model. And can I easily get events on a certain date from a 'datetime' value?
There a lot of ways to go about this, here is one option:
Since you want to see multiple events, you'd probably start off focused on the index action. Start off by creating and index action, but add some hooks to filter it, i.e.
def index
if params[:sport]
#events = Event.where("sport = ?",params[:sport])
else
#events = Event.all()
end
end
Now, if you've defined your routes like this:
resources :events
You'll have a a route /events that will accept a get request and route you to the index action.
But if you want a form where you can select things, a form will by default POST, but you could create a form that GETs to '/events'
i.e. in app/views/events/index.html.erb
<%= form_tag '/events', :method=>:get %>
Then, you want to create your form elements that will send the params.
i.e.
<%= select_tag 'sport', '<option>baseball</option><option>football</option>' %>
Put in a submit button
<%= submit_tag 'See Events'
Then 'end' your form with
<% end %>
Now when you click on the 'See Events' button, you will send a get request to the route '/events', and the 'sport' parameter will show up in the index action, filtering the events.
To keep things simple and all in the index view, after your form you'd list all the events.
<% #events.each do |e| %>
Sport: <%= e.sport %><br/>
Home Team: <%= e.home_team %><br/>
Away Team: <%= e.away_team %><br/>
Time: <%= e.time.strftime('%H %M') %><br/>
<% end %>