Saving data in rails session to use in form on next request - ruby-on-rails

Let's say I have a table called positions (as in job positions). On the position show page I display all the detail about the job - awesome. At the bottom I need the prospective applicant to input their professional license # before continuing onto the next page which is the actual applicant creation form. I also need to take that license # and have it populate that field on the applicant form (again on the proceeding page).
I realize there are a couple ways to do this. Possibly the more popular option would be to store that value in the session. I am curious how to do this in the simplest manner?
My idea:
Create a table specifically for license #'s.
Add a small form on the position show page to create license # (with validation)
Store newly created license in session - not sure what to put in which controller?
On applicant creation form populate from session the license #.
This would assume applicants only have one license.
Thoughts?
Appreciate the help!

Don't store this in the session! Pass that as an hidden field.
Let's say the user starts the form, then open the form again in a new window or something... then the session variable would be shared between the two forms. Other problems would occur if the cookie gets removed (session expire, user clear cache...)
This is not good. The best way is using a POST variable. GET works as well but messes up the URL

Seems like a good idea. As for #3, for whatever controller is called in the transition from 2 -> 4, that would be the controller where you store the session, as such:
session[:license_number] = your_license_number_information
From there, it can be called the same way (session[:license_number]) to get it.

The hidden field is safer for data persistence. However is not not then coded in the HTML output? That can be a great data security issue.
This is a trade-off to be considered.

Related

Proper way to remember multiple parameters across requests in Rails

My application feature a "main" page where most of the action happens: There are tags for filtering and a list of results in a (paginated) table, plus the possibility to select some or all results in a "shopping cart".
This page has to keep track of a whole lot of things: what tags are selected, what items are selected, and how the result table is sorted and what page it's on. Everything has to persist, so if I select a new tag, the page must partially reload but remember everything (sorting, what's selected).
Right now I'm handling everything with parameters, and for each action taken on the page, all links (select a tag/item, change page, sort table) are updated to include previous parameters + the relevant new addition. This works, obviously, but it feels kind of inefficient, as I have to reload more of the page than I want to. How is this situation normally handled? I can't find that much info on google at all, but it doesn't feel like a particularly uncommon case.
tl;dr: How to best make sure all links (to the same page) always include everything previously selected + the new action. There are a lot of links (one per tag to select/deselect, one per result item to select/deselect, one per sort option, one per page)
There are five ways to do that:
Method 1: By parameters
You mentioned this. I never think of this as it's too troublesome. Anyway it's still a solution for very simple case.
Method 2: By cookie
Save the settings to a cookie and read the cookie in controller to arrange layout settings.
Method 3: By LocalStorage
Similar to cookie but allows more space.
Method 4: By Session
If you are using ActiveRecord to save session, this could be the best solution for pure pages loading. Save the user preferences into session and load it in next layout.
Method 5: Use Ajax
This is the best solution IMO. Instead of whole page loading, use Ajax to refresh/retrieve changes you need. Using together with above method, a user can even continue his last preferences. This is the most powerful and should be applicable to your case which looks like a web app than a website.
Have you tried creating model for all those attributes? and just always load the 'latest' when on the page load, if you dont need them you can always have a flag for that session.

Update param and call action in controller on click?

I have been banging my head over this for the past 3 days (No kidding!!!)....It seems like a very simple thing but I am just unable to do it. So I'm putting the question out here, and am open to any method which would work.
BACKGROUND : An advanced search form on submission used to generate an URL too large for the server. So the form had to be submitted via POST. So far, so good. Form submitted successfully, and the result was displayed. Only remaining problem was pagination.
As it's a POST call, it ruled out will pagination. While will-pagination merges param page to the existing params, but the problem is that it shows on url which results in the same error.
QUESTION: So is there any way, if the user clicks a link NEXT, I can
a) Update the page param
b) Keep the existing params
c) While not changing the URL
d) Transfer control back to the action in controller?
The only solution so far suggested was have a hidden form, repopulate it's value and submit again. The form's pretty complex, so if there is a cleaner way I'd like to know.
I see what you want from your comment. So editing my reply accordingly. You want the information as to which column is being selected in the sort to be available to the controller without having that information available in the url string, and you want to use GET for this not POST
The challenge you have is that you want to preserve state between requests and you need a mechanism for doing this. POST preserves that information by sending it in the body of the POST request. GET does this by allowing you to populate the query string. The other method for preserving state is to use a cookie.
You can manipulate the url with javascript on the page. There are tutorials online for that.
But if you just want a simple controller hack as you say in your comment then the simplest one I can think of is to allow the user to make the GET request to the url with the query params in it, then handle this request in two steps - step one saves the query information to the cookie, step two redirects them to the url with that query string data stripped, and you look on the cookie to see if it has those fields before building your data for that page. It's hacky but it works.
def sort
session[:sort] = params[:sort]
redirect_to url_without_the_query_string
end
There is also the new html 5 feature:
window.history.replaceState(“Replace”, “Page Title”, “/mypage”);
from this stackoverflow answer here: How to remove query string from url using javascript
However I'm not sure I'd recommend messing with the url after load like that (I don't know enough about that solution so I'd recommend you read that answer and see if that fits). So, if you MUST lose that data from the url string, because you need to somehow pass it between requests you either have to use POST, or use the session cookie/redirect method I describe above.
Does your html <form> have an action attribute? If not, add one that points to the page.
If you want to preserve the current GET params so that results from the POST can use , you will also need to modify the javascript triggered on the heading links so that as well as (or instead of) modifying the query string, they write the same data to hidden form fields (which of course then get posted in the body of the request). Your JS library may already include helpful functions for that.

Response comments added to the wrong parent document

I have a view data source that uses a view key to access documents and show them in a repeat with var "posts". within the repeat I have a document data source with var "post" that gets's the the unid of the documents using posts.getUniversalID().
further down the repeat I have another document data source "newcomment" that is a response and take the parent id as: post.getDocument().getUniversalID()
below the newcomment data source I have an editbox and a submit button which saves the comment as a response to the "post" using newcomment.save()
Here is my problem
two people access the same xpage. personA enters the page and starts writing a comment to a post. in the same time personB creates a new post and submit it before personA submits the comment. What happens now is that the comments gets binded to the latest post and not to the post personA responded to.
I tried anothoher thing also, let's say there is 10 posts in that database. personA and personB access the xpages. personA start writing a comment to post number 8. at the same time personB creates two new posts in the database. when personA now submits the comment it seem to get bind to the same index which is now two posts up. but still index 8. which is ofcourse the wrong post.
If I change the repeat to "createControlsAtPageCreation" ie.e repeatControls=true the comment is attached to the correct post but then I run into another problem that the view is not updated to show the latest posts.
my repeat is wihtin a custom control that is loaded dynamically using the dynamic content control in extlib.
As information here is what I have found about the repeatControls settings
Setting the repeatControls property to true instructs the repeat control to create a new copy of its children for each iteration over the dataset.
When the Repeat control is configured with the property
repeatControls=“true” , it repeats its contents only once, at page load time
So my question here is that I do not understand what is going on. why is my comment attached to the wrong parent document? and is there a way I can prevent this and still have new posts displayed correctly
thanks for your help
Without the code it's a bit hard to imagine what exactly is going one here but this looks very similar to problem that I had with repeat control and value binding.
Long story short the problem was connecet to repeatControls property set to false. When it was like that data binding were working only for first element in collection - all data was somehow magically saved to this first object! I managed to get this working by using combination of dynamic content control rebuild and repeatControls set to true. Only then databindings were working property.
It seems like if You are repeating rendering only (and this is what repeatControls set to false do) the decoding phase of jsf lifecycle goes foobar.
Without your XSP markup, it's difficult to be absolutely definitive but it appears that you're app code is creating and persisting the datasources and components per row during page load - therefore increasing the overall size and complexity of the component tree also. You should alternatively try an approach that will lazy-load the datasource only when requested by the end-user (eg: edit / reply).
Refer to the XPages Extension Library demo application (XPagesExt.nsf) for examples that use such a dynamic approach. In particular, look at Core_InPlaceForm.xsp which demonstrates using the xe:inPlaceForm control within a xp:repeat. And also see Domino_ForumView.xsp which demonstrates using the xe:forumView and xe:forumPost controls to manage and visualize a hierarchical thread. Also consider the concurrency mode that best suits your requirements when it actually comes to saving any given post or comment (fail, createConflict, force, exception) and document locking for high contention situations. The above-mentioned controls all provide the highest level of dynamic control and datasource creation and destruction.
Please feel free to send me on a worked example database, where I can understand your exact use case - DM me or email me.

Rails validation fails but object memory remains unchanged?

First time user long time reader. I have thoroughly looked for an explanation for the problem I'm having via the mighty search engine Google, but alas I have failed to produce any significant insight.
I need to be able to ensure that a model form is not reloaded with invalid data. Since the model stored in memory on the server is edited directly with the parameters of the web form first, and THEN checked for validity, without additional code invalid model data will ALWAYS be sent back to the form. This is less than desirable to me. My question is this: how do I ensure this doesn't happen?
What I'm thinking is I need some mechanism for saving the state of the object before it's modified with the parameters sent from the web form, and then after a failed validation restore the object to it's previous, correct and unmodified state of being.
Help!
Thanks,
Les
The object isn't actually modified in the db if validation fails, even though the object is in an invalid state in the form ... the thinking behind this is that the user wants to see the errors they made so they can correct them.
If you don't want that to be the case, then just read back the object with a WhateverObject.find(x) and assign it to the variable that the form is referencing and it will 'restore' the object to its previous unmodified state.
To add to what concept47 said you can also get the value for a particular field using
object.field_was
Have a look at ActiveRecord::Dirty for details (http://ar.rubyonrails.org/classes/ActiveRecord/Dirty.html)
Using that you could retrieve the original values for just those fields that had validation errors.

(Rails) Managing a tree without javascript?

I'm looking for some non-javascript techniques by which to reload a page of tree items (basically divs within divs) while remembering their "show/hide" status. So far the only thing I can think of is to pass every entity's ID as part of a parameter list and have Rails then insert a "class-display" in the class list (or, of course, directly append the appropriate css) when the page reloads. In any case, is there a better way by which to manage these items?
Basically my goal is to be able to show/hide the tree whether JS is enabled or not.
Best.
I would seriously consider implementing this with cookies. It's not exactly critical data, as in the world isn't going to end if someone deletes a cookie and collapses their tree. It will also avoid having to spew state information all over your query strings.
When opening a new branch, your controller would add a new cookie that marks as "open" whatever div id needs to be expanded. Closing a branch would be the reverse -- controller deletes / modifies the cookie.
Then when rendering your view, use the cookie info to decide which divs should have their display style set to "normal" or "none".

Resources