Updating multiple records in a single submit? - Rails 3 - ruby-on-rails

I'm a newbie to rails and am having some difficulty...
I have a page displaying a list of records in a table and would like for the user to be able to make changes, submit the form, to run validation and persist the data.
This is what I have so far:
View:
- #people.each do |p|
%tr
%td
%input{:type => "hidden", :name => "person_id[]", :value => p.id}
%input{:name => "firstname[]", :value => p.firstname}
%td
%input{:name => "lastname[]", :value => p.lastname}
Example parameters being posted to the controller:
"person_id"=>["12", "13", "14"],
"firstname"=>["john", "joe", "mary"],
"lastname"=>["smith", "bloggs", "jane"],
At this point I am scared, because I am no longer bound to an active record. Instead I feel myself wanting to write some messy code to loop over the person_id array to see what has changed and write any changes back.
This feels bad because I have to explicitly compare each field, also if something fails due to a validation error half way through how should I rollback any changes and display the messages to the user?
I'm hoping that due to my rails ignorance this whole approach is wrong and I am missing a trick. Does anyone have any suggestions for how to approach this problem?

I suppose you have an association setup between people model and person model, by looking at the hidden person_id field in your view code.
If your associations are rightly setup, use
accepts_nested_attributes_for
and follow the Rails guides for association basics.
At this point of time, I can only help you this much, as not much information is provided in your question.

Related

rails association populate field from another table

Hoping this will be a straight forward question, but is anyone able to let me know the best way of populating a hidden field based on a value on another table.
I currently have 2 tables - table_numbers which has the following fields - id and value(decimal), and table_records which has an amount field.
On the form to add a new record I have the following to add a value to it
= f.association :table_number, :collection => table_numbers.order('value ASC'), :label_method => :value, :prompt => "Select a value", :label => "value"
At the moment this is populating the number_id on the records table, but displaying the value on the form when adding a record. What I would like is to get the value as well to be able to run a calculation on the value and amount.
What would be the best way to do this? Update the line above or do I need to add extra code?
Thanks
You can perfom calucaltions in before_save callback in model. If you want to display calculations, use helper and show it.

Ruby on Rails: Nested Model Form Checkbox For A 'has_many :through' Relationship

Still fairly new to RoR, let alone Ruby itself.
Here's my issue. I'm using Rails 4 and Ruby 2.1.0
I have a User class with this relationship:
has_many :roles, ->{ uniq }, :through => :user_roles
accepts_nested_attributes_for :roles
Now, the table 'roles' simply has a list of roles, such as 'admin', 'moderator', 'visitor', 'artist', etc.
The table 'user_roles', is just a relational table, with the role's key and the user's key.
So, to clarify, 'users' has a one to many relationship with 'user_roles' and "user_roles' table has a many to one relationship with the 'roles' table.
Something like this:
users: id, name, email #ie: 12, 'mikey', 'mike#foobar.com'
user_roles: id, user_id, role_id #ie: 4324, 12, 8
roles: id, name, weight #ie: 8, 'moderator', 11
I've been given the task of adding a checkbox toggle in the admin section so that an admin can grant the moderator role to any one user.
Each admin page is for one specific user. Therefore, the form_for is based on the #user instance, depending on which user the admin selected for editing.
RailsCasts #196 kind of helped me understand the concept, but it's platform is just different enough that I'm not sure how to exactly translate it into what I need. Likewise, there are some similar questions here on StackOverflow as well - but again, I can't seem to get it to translate correctly into my situation.
What I do have, I think should be at least somewhere in the realm of the right direction. THen again, maybe I'm way off. Here is my form code:
= form_for #user, :url => admin_user_path(#user), html:{class: 'form_horizontal'} do |f|
%br
%h4{class: :dc_green}Logistical Information
= f.label :display_name, "Display Name"
= f.text_field :display_name
= f.label :email, "eMail"
= f.text_field :email
%br
= f.fields_for :roles do |a|
= a.check_box :moderator, { inline_label: :none }
= a.label :moderator, {for: :moderator, class: "checkbox inline"}
%br
The error I'm getting with this form code is: undefined method `moderator'
Thank you in advance for anyone who can offer support :)
I guess I should probably add that I'm also clueless as to how I should handle this in the controller once it is submitted. But, first things first.
UPDATE
So, the reason I'm getting the undefined error is because it doesn't exist for that user. Which is bad. I need to be able to add the role to the user or remove the role. However, the only roles coming through are the roles the user has already been assigned to. So I'm totally doing this wrong. Now I'm really in the dark.

Formtastic and belongs_to association

I am trying to learn by doing and need some help.
So formtastic can handle belongs_to associations (like Post belongs_to :author), rendering a select or set of radio inputs with choices from the parent model.
What I am trying to do is create a post without having to select the author in the create form.
I want to set the author id via a hidden form field but when I try this
<%= f.input :author, :as => :hidden, :value => '33' %>
I get uninitialized constant author and tried various other ways that Ive failed to get to work.
The closest Ive got has been by trying to customise the choices for the select and hiding the select as follows:
<%= f.input :author, :as => :select, :collection => ["33"], :input_html => { :style => 'visibility: hidden' } %>
But even though the above hides the select and works, it still displays a form label for author which I dont want it to display
Here is an example to better explain my scenario if what Im trying to achieve is still unclear:
Imagine you have a list of authors page and as an author you click on your name to get into an area where you can manage various things and create posts.
The problem: When you click create a post and the form renders, you dont want to have to select your name from one of the fields to tell the app that the post you are creating belongs to you because you want the system to know its yours because you are in a config area that belongs to you.
I am trying to do this by using a hidden form field to set the author id so that the post is saved with the correct association when the user submits the form.
Can anyone provide me with an example of how to do this? and as Im a learner maybe there is a better way to approach this so can anyone please advise and point me to some good examples
You should not be populating it in a hidden form field; hidden form fields can still be changed by the user and in the end you are allowing users to create posts by other authors.
The correct way to do this would be to assign #post.author = current_user in the create action of your PostsController.

Cannot precheck check_box_tag in rails

I have code that looks like this:
#all_ratings.each do |rating|
= check_box_tag "ratings[#{rating}]", session[:checkbox][rating], :id => "ratings_#{rating}"
...
= submit_tag 'Refresh', :id => "ratings_submit"
By saving the state of which checkboxes were clicked I hoped to be able to pre-check the boxes that were clicked after the request had gone through and the page reloads. The problem that I am having is that the code above doesn't seem to work. I'm not sure if it's because I have the :id => "ratings_#{rating}" bit at the end (which is required for this assignment). I checked out the rails api here, but that was as clear as mud. Thanks in advance for the help!
Cheers
(Disclaimer: This code is for HW 2 for Coursera's Software as a Service course - I have finished the bulk of the logic for the HW, but this last bit is beyond me and seems to be more of an idiosyncracy than a major topic, hence I am posting it here.)
What boolean variable did you add? Considering I have a model with has_many ratings, say Video, and have #video defined, I'd do
= check_box_tag "ratings[#{rating}]", session[:checkbox][rating], #video.ratings.include?(rating), :id => "ratings_#{rating}".
The #video.ratings.include?(rating) part prechecks the ratings associated to the current video. What are the associations related to your Rating model?

Formtastic non-model form, integration with external site, override/specify the input ID values

I'm using formtastic to collect information from a form and post dirctly to an external site.
I have no problem generating the form itself. However, since this is being submitted to an external site, they require that each input field have the specific IDs they specify, eg email or last_name -- not the closest Formtastic form, eg _email_input or _last_name_input.
I've looked at the Formtastic v1.2.3 code and I'm 90% sure the answer is "sorry, can't do that." I figured it couldn't hurt to check if I'm missing something. I would like some way to specify the ID completely, as in:
= semantic_form_for('', :url => "https://external_site.com/handler, :method => "post") do |form|
= form.input :last_name, :id => "last_name"
[etc]
Is this possible?
(I will note that I recognize that another, arguably superior approach would be to create an appropriate controller, sanity check the parameters locally, and dispatch the remote call from within the app only when it's well formed; however, that's not what I'm trying to do at the moment.)
Firstly i think you need to use semantic_fields_for for non-model forms. Next, to pass ids to each field, you can use the input_html options to specify them. for eg
form.input :email, :input_html => {:name => 'email', :id => 'email' }

Resources