Rails - Submit multiple forms on same page - ruby-on-rails

Model:
Users have expenses. Expense has a status.
View:
As users add their expenses, they are shown in a list. Each expense row has a form button on the end, which is used to submit the expense (changing the status of the expense). This allows users to add expenses they have not completely filled out, and submit them when they are ready. There is no parent form on this page, just the form buttons which submit the expense to a method which changes the status, and then reloads the page.
Currently it works great, but users have asked to be able to "submit all" the expenses that are showing on the view with a single button.
Question:
What is the proper way to handle this in rails? Should I find a way to gather the array of expense id's and then submit a separate form? Is there a way to ask for a set of records present in a view with a certain status?
Thanks!

Another option, if I'm thinking about this right (big if), would be to wrap your page in a User form. Then you could have something like...
<%= form_for(#user) do |f| %>
<% #user.expenses.each do |expense| %>
<% f.fields_for expense do |e| %>
<!-- expense form -->
<% end %>
<% end >
<% end %>
This is something you could submit as a whole. I'm having trouble picturing what a single expense addition might look like, but hopefully this gets you a little further down the road.
Edit: in addition to having this User form on the page, you could have an "extra" Expense form to create an expense. When you submit a new expense, that expense appears in the list under the user form, where it can be edited or submitted, either as part of a group or individually (as part of a "group" of 1).

custom controller action:
def update_all_expense_statuses
expenses = current_user.expenses
ExpenseUpdater.new(expenses).update_expense
redirect_to :back
end
expense updater class:
class ExpenseUpdater
def initialize(expenses)
#expenses = expenses
end
def update_expense
#expenses.each do |expense|
expense.update_attributes(status: 'paid')
expense.save
end
end
end
This is just an example of one way to update all the user's expenses with a custom controller action. Just call the controller method from a link_to:
<%= link_to "Update all expenses", update_all_expense_statuses_path %>
Remember to add it to your routes. Hope this helps.

The first thing you should do is change the forms to submit remotely, ie make an ajax request. Then you're not reloading the whole page. Check out Rails' various "remote" form helpers, eg "remote_form_for".
Then, write a javascript function to submit all the forms for inputs that have changed since the page loaded. You'd probably want to add a "changed" (or similar) class to the parent form in an onchange event in each input, to facilitate this. I think this is the best way to handle the "status" thing you're asking about. Make a "Submit all" button which calls this function.

Use a form/service object http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ to encapsulate expense report

Related

How do I create a drop down in a Rails form where the user can change the default value?

I'd like to have a drop down in my Rails form where users can select an area of a city, e.g. "Marchmont", "New Town", "Baberton" etc, when adding an order. I'd like that once they have made a selection, this will then be the default selection for the following times they use the form to add an order (so that they don't have to keep selecting it) but also that they can change their selection at any time. Hope that makes sense. I'm using the Simple Form gem. Thanks in advance! :)
#Steve
I will make a couple of assumptions.
1.) you know how to create forms within the rails templating engine.
2.) you understand how to create a dropdown menu using the Simple Form gem
So you have a couple of options based on what you actually want to accomplish. Based on what you are briefly describing, it sounds like you have some kind of an e-commerce/checkout situation that you want auto-completion to make it easier for a user.
there are a couple of approaches to storing this data.
Saving the user Data.
1.) Save it right on the user model under district_of_last_order
2.) Save it right on the order model that a user has_many orders. Then you can pull the first order's city district and select that
Personally I would lean on #2 as you probably want to be able to tightly couple the order with the user and saving that information twice is redundant since you can always do something like current_user.orders.first.district or whatever,
in your ERB where you build the form you can then do something along these lines:
<%= simple_form_for(#order) do |f| %>
... other input fields
<% if current_user.orders.first %>
<%= f.input as: :select selected: current_user.orders.first.district %>
<% else %>
<%= ... your regular dropdown menu here without the default %>
<% end %>
... rest of your form
If you have the option of using gems, I have had good results with select2-rails.

In Rails, how to update record from show view (and not edit)?

After many googling, I can't find something relevant...
I have a student model with view (edit, index, show). Edit view are only viewed by student and index and show views are viewed by admin staff.
I would the admin staff could check a checkbox on the show view to "sign" or say "done" at this record.
If the check box is checked, i would a "sign information" like time.now and current_user name.
I should save this in the student record. How to do that because show is a "get" form and I would a "post" action...
Could you help me ?
Many thanks in advance
Nicolas
The name of the page is not relevant, you can put a form or "action" link any page. To just show something to administrators, you could create a method admin_user in a helper file which checks if the current user is an admin, and then put the following code in your view:
<% if admin_user? %>
<%= link_to "Check", sign_path %>
<% end %>
You could then create a route and controller action "Sign" which will mark a specific record as signed. You could also use a form in the above code.

Rails - Dynamic Nested Forms for Only One Element

I've to modals teams and players, and as usual team has many players.
In teams' show page, I'm showing the players and so on. (I've followed railscasts.com/episodes/196-nested-model-form-part-1 tutorial.)
My problem is, when I click on the player's name in team show page, I would like to show team's edit form but with only clicked player's data in it.
In current case, I have huge form which has all players' information.
That would be great if you can help me.
Thanks.
You could put a hidden_field in your team form that passes the player_id to the controller as a parameter when submitted.
In the controller you could then perform a search only for the params[:player_id] and change your view s you display that.
In your form:
<%= form_for .... do |f| %>
<%= f.hidden_field 'player_id', value: player.id %>
...
<% end %>
In your controller:
if(params[:player_id])
#information = Information.find_by_user_id(params[:player_id].to_i)
end
And, finally, in your view, you can display the #information variable as you wish.
If you dont want to submit to your controller write a javascript program:
$(document).ready( function () {
$(".team_form").live("click", function() {
$(this).attr("player_id").val //holds the player_id
//load the other form using the player_id
}
}

Rails Dependent Form - Selecting a Specific Item from a Model

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 %>

Rails Forms and Associations - Adding multiple objects with a quantity form

I am new to rails, but not to programming or databases.
A BETTER PHRASING OF MY QUESTION IS IN MY ANSWER BELOW.
For simplicity in this example, I have 3 models:
User
Subscription
Default_Subscription
User has_many Subscriptions
Subscription belongs_to User
Default_Subscription has_many Subscriptions
Subscription belongs_to Default_Subscription
Default_Subscription is a pre-populated table with certain types of subscriptions.
During the subscription process, the default subscriptions are listed at one point, and there
is a quantity box alongside each one.
The user enters the quantities for each subscription and hits submit to continue on.
My question is:
How would one go about creating a new subscription for each quantity in a number form?
So you would have a list something like so:
<ol>
<%= each subscription with quantity box %>
</ol>
<%= button_to %>
When the user hits the button, how do you add up the quantity from each box and add a new subscription for each one? Do I have to use javascript to get the numbers? Do I somehow use rails forms even though this quantities are not associated with any specific database field? Any recommendations or pointing me in the right direction to figure this out on my own would be great.
This form box IS NOT A FIELD FOR ANY MODEL, it's a count for an association. Let me rephrase: Each quantity in the form boxes represent the number of NEW Subscriptions to be created. Each of these subscriptions BELONGS_TO 1 DEFAULT_SUBSCRIPTION. In essence, the number represents the number of new subscriptions ASSOCIATED WITH THAT DEFAULT SUBSCRIPTION.
I'm using rails 3.2.1, and ruby 1.8.7
Thank you
Not sure I totally understand your description, but I'll take a shot.
Use the 'form_for' function to build your form, based on an instance of #default_subscription (established in the "new" action in your controller). If there are default values in #default_subscription, will show in the fields and the user can change them as they see fit. (this assumes your DefaultSubscription model has three attributes: sub1, sub2 and sub3.)
<%= form_for #default_subscription do |f|
<%= f.label :sub1 %><br />
<%= f.number_field :sub1 %>
<%= f.label :sub2 %><br />
<%= f.number_field :sub2 %>
<%= f.label :sub3 %><br />
<%= f.number_field :sub3 %>
<% end %>
When the user clicks the submit button the contents of the form with we assembled into a hash and passed into your controller's "update" action via params[]. You can extract the subscription hash like this:
user_subscription = params[:default_subscription]
At this point you have all the numbers that the user entered into the fields in the user_subscription hash. You can now parse the hash to extract the numbers, do your math, and then create the appropriate subscriptions per the user's input. (one note: the numbers could be strings and you might need to convert them back to integers as I've shown below.)
For example, to total all the subscription values and save that total into a user's subscription:
total = 0;
user_subscription.each do |key, value|
total += value.to_i
end
new_sub = current_user.subscription.new
new_sub.total = total
new_but.save
As I said, I don't understand your description clearly, so this might not be germane, but hope it is close to what you were looking for.
Good luck.
I have figured out one way, and reading my original post again, the whole thing is really confusing because I didn't know how to say exactly what I was trying to accomplish. I must say a lot of the reason I was confused is because the form I wanted did not correspond to any model, just an association count, which is ultimately a basic html form if you want to create a bunch of new objects without having their attributes yet. I'll first clarify then show my solution.
Clarification:
I have 2 Tables:
Subscription
Default_Subscription (Pre-Populated)
Subscription belongs_to Default_Subscriptions
Default_Subscription has_many Subscriptions
A User is subscribing to my website. This process is a step by step: not everything happens on the same page.
This all happens in a subscribe_controller. Each action corresponds to a step in the process.
One of the actions is default_subscriptions. This action lists the Default_Subscriptions a User can choose from, except they do not just choose, they can enter an amount for each type of Default_Subscription they'd like.
When the Default_Subscriptions are listed on the default_subscriptions page, I wanted a form with an html number input alongside each of these Default_Subscription. When the form is submitted via a next button, I had no idea how to gather the quantities from each html input and create an array of Subscription.new, with each Subscription's default_subscription_id corresponding to the proper Default_Subscription.
One Possible Solution:
def default_subscriptions
#def_subscriptions = Default_Subscription.all
end
Lets say the page I want proceed to after all the quantities are entered on the default_subscriptions page is review_subscriptions.
Here's what I did to create the proper form to proceed to the next action in the controller:
<%= form_tag( {:controller => 'subscribe', :action => 'review_subscriptions'}, :method => 'post' ) do %>
<ol>
<% #def_subscriptions.each do |ds| %>
<li>
<%= ds.name + ' ' %>
<%= number_field_tag("subscription_counts[#{ds.id}]") %>
</li>
<% end %>
</ol>
<%= submit_tag('Next') %>
<% end %>
The trick here is that string passed to the number_field_tag. By placing a single set of square brackets at the end of the string for a field_tag method parameter, the part before the brackets is the name of the hash, and the thing in the brackets is a key in the hash, and the submit button causes the corresponding value for each key to be the value of the field. Pretty cool!
The parameters passed to the next action would contain a hash called subscription_counts, and iterating through this hash would give a corresponding new subscription amount for each default_subscription_id. Like so:
def review_subscriptions
subscription_counts = params[:subscription_counts]
subscription_counts.each do |id, amount|
counter = Integer(amount)
until counter == 0
new_subscription = Subscription.new
new_subscription.default_subscription_id = Integer(id)
#subscriptions << new_subscription # #subscriptions is an instance variable
counter -= 1
end
end
end
I'd just like to point out, the more I work with them, the more I love them; I love Rails, and I love Ruby. They are super fun and classy. An until loop... how cool is that? If you have other solutions, now that my question is more obvious, please chime in! I know others out there are trying to find some slick ways to create multiple new objects in a one to many association with a single post call like this. Technically my objects aren't saved in the database yet, but that wouldn't be to hard now.
The main reference which helped me the most in reaching this solution was:
http://guides.rubyonrails.org/form_helpers.html
If you are new to rails, and confused about forms, read this. I feel like a master now. Rails devs are really good at documenting things!

Resources