I'm doing an ajax call to save data.Now the issue is that user might unknowingly submit the same data twice and it will become duplicate. Is there any shortcut or validation for abandoning the user from submitting or saving the same data twice?
Also please note that created_at,updated_at will not be same when the user submits the form for the second time. Also the only thing that can be unique in my table is ID :) .
If I have 10 form fields and until and Unless all the 10 fields of my form are same the validator will not reject the data.
You can use an attribute like 'title' and check if it's uniq for that user :
class SomeModel < AR
validates_uniqueness_of :title, :scope => [:user_id]
end
I do not think there's a reasonable solution of this problem on the server side.
Try a simple magic of javascript disable_with.
Related
Good Day All!
Edited for better understanding.
First model is Inventory and in this model I have Product_Type, Product_Name and User_ID.
Second model I have Users which consist of First_Name, Last_Name and Pin_Number.
On my Inventories page I have a form for checking out said Product_Type and Product_Name, also a place for a user to put their Pin_Number in. On submit, it will check the Pin_Number they have typed in and validate it in the Users model and if the Pin_Number is correct it will create an entry with said Product_Type, Product_Name and User_ID (which is pulled from Pin_Number that was submitted.)
I am just trying to figure out how to validate that Pin_Number they submitted.
Thats why I thought I had to do some kind of validation and an if statement based on that validation. Not sure how to go about that.
I hope this clears up any confusion.
I am just trying to figure out how to validate that Pin_Number they submitted.
What constitutes a valid pin_number? Just that it allows you to successfully look up a User? What if a user enters another user's pin_number? Is that considered 'valid'? Something to think about...
It would be helpful if you would add to your question what your params look like upon form submission. But, we can do some guess work.
So, let's assume that params looks something like:
{..., "inventory"=>{"product_type"=>"foo", "product_name"=>"Bar"}, "pin_number"=>5, ...}
In your controller, you'll probably do something like:
if #user = User.find_by(pin_number: params[:pin_number])
#inventory = Inventory.new(inventory_params)
#inventory.user = #user
if #inventory.valid?
#inventory.save
# perhaps do some other stuff...
else
# handle the case where the `#inventory` is not valid
end
else
# handle the case where the `#user` was not found
end
This assumes you have something like:
private
def inventory_params
params.require(:inventory).permit(:product_type, :product_name)
end
In your Inventory model, you probably want to do something like (I apologize, I'm not on Rails 5 yet, so some of the syntax may be incorrect):
class Inventory < ActiveRecord::Base
validates :user_id,
:product_type,
:product_name,
presence: true
belongs_to :user
end
You probably also want to consider adding an index on User.pin_number if you're going to be doing a lot of finding by it.
Not sure if I got the question right, but sounds like a custom validator to me.
You can learn more about custom validators in the official Rails documentation under "Custom Validators"
Also, consider moving the class for the custom validator you'll build to a concern, which is a great way to make it reusable. You can find more information on this StackOverflow question and this nice tutorial.
I have an app with the following tables:
Courses,
Exercises,
Answers, and
Users (with Devise).
class Answer < ActiveRecord::Base
belongs_to :exercise
belongs_to :user
end
Each exercise has an html answer box and a "submit" button, but I want to know if the data submitted by users through the answers in each exercise goes somewhere or what can I do to retrieve it?
What would I need to do to have the answers saved somewhere where they can reviewed, or even maybe sent by email?
I know like html forms that are sent by email when you hit submit, but would that indicate which user submitted the answer?
I appreciate your help!
For your current scenario you must have exercise_id and user_id column in your answers table.
When you submit a form for answer you must have exercise_id present. And you will easily get that from controller while you are showing exercise to answer.
Now for user_id, If you are using devise than you are getting current_user object every where in your application after login.
So to save answer you must write something like this:
current_user.answers.create(params_answer)
And params_answer should be something like:
def params_answer
params.require(:answer).permit(:exercise_id, :answer_text, :xxxx, :yyyy)
end
To get answer of any qustion that current user submitted:
curren_user.answers
To get answers of perticular exercise
curren_user.answers.where(:exercise_id, '##')
For more info go through http://guides.rubyonrails.org/association_basics.html and http://guides.rubyonrails.org/active_record_querying.html
Although I don't understand your words clearly.
Using session may help.
Just trying out Mongoid at the moment, I've run into an issue that's probably pretty simple but has me at a loss:
I have a really simple Article model:
class Article
include Mongoid::Document
field :title, :type => String
field :content, :type => String
key :title
referenced_in :subject
validates_presence_of :title
end
I added key :title after I had already created one test record. Newly created records work as expected, but the first Article (which originally had the normal mongoid object id) behaves strangely:
In rails views this first article still returns its object id instead of the new key. ie using link_to article.name, article returns:
Show
... when all the rest return the parameterized keys, like:
Show
If I click that link I get "Record not found". I tried loading and resaving this record in the console, and after that calling article.id on that record did return the parameterized key, but it still shows up the old way in the view and doesn't work.
So, a couple questions:
What's going on here?
How do you fix it?
This situation indicates to me that if you set a field on a mongoid model to be the key, you need to be really sure that it will never change. How do you handle something like using the title of an article as a slug, then, when those may occasionally need change?
Thanks!
Well, since _id is immutable, your only option is to reinsert this document with your new 'sluggish' id and delete the old one.
And yes, _id format and shard key (if you use sharding) are the two things you better have right from the beginning :-)
Everything else can be fixed relatively easily.
I am not finding any great examples online and so am asking an easy question for what I expect will get an easy answer. Be gentle. :)
I have a Post model.
p = Post.find(1)
p.title = "This is the Title of this Article"
p.url_title = "this-is-the-title-of-this-article--created-by-user-name"
When the Post is created, I create the :url_title based off the title. This is how I key off it in the database rather than exposing IDs which are also boring and non-descriptive.
I build this :url_title in a before_save so that is why I can't simply use 'validates_uniqueness_of' because it looks like the validations are done before the before_save kicks in and there is a :url_title to validate.
So, I need to ensure that :url_title is unique. I append the "--created-by-#{p.user.name}" to allow for there to be multiple uses of the same title from different users.
So, what I need to do is have a custom validation that confirms that :url_title is unique to the database before saving and, if it is not unique, raises and error and informs the user.
Thoughts on the best way to do this?
'
You can move your callback from before_save to before_validation (see here). This callback will be run on create and update action, so I think it will be sufficient for your needs.
Use this to create the url_title
before_validation_on_create :create_url_title
....
private
def create_url_title
url_title = .....
end
Then add the proper validation to url_title
validate_uniqueness_of :url_title, :message => "This title is taken, please choose a different title"
Just add
validates_uniqueness_of :url_title
in your Post model
I'd like to create a user registration form where the user ticks some boxes that do not connect to the model.
For example, there might be a 'terms & conditions' box that I don't want to have a boolean field in the User model saying 'ticked Terms & Conditions'. Instead I want to create a record somewhere else (like a transaction) that recorded the date/time they accepted the T&Cs.
Another example might be some preference they indicated that I'll use later and hold in the session for now, like 'remember me'.
I can mix these types of fields with the regular form helper. How could I do either one of the examples above when using formtastic? It kind of sticks to have to mix traditional rails tags with lovely clean formtastic code.
You can create any number of virtual attributes in your model that do not necessarily need to be tied to a database column. Adding attr_accessor :terms_and_conditions to your user model will make this 'field' available to formtastic -- even though it's not a database field. You can validate it like any other field or create your own setter method to create a record elsewhere if that's what you need.
I'm inclined to disagree with the approach to use attr_accessors for action-specific entry elements. If Ts&Cs need to be recorded then that makes sense, but sometimes you need data that really is unrelated to the model and is only related to the specific action at hand, such as 'perform some heavyweight operation when executing the action'.
Lets say you have a sign-up form, and you're not using OAuth, and you have an option to specify twitter username and password on sign up. This is fine:
<%= form.input :twitter_username %>
<%= form.input :twitter_password, :as => :password %>
But this bit below confuses me -- its like formtastic in this case is actually taking away what is already there. Is there a way of adding params[:your-object] while still getting formastic to do all its lovely layout stuff?
How about:
class User < ActiveRecord::Base
...
#I don't want this here. Its only for UserController#create.
#attr_accessor :tweet_when_signed_up
...
end
and:
<%= form.input :tweet_when_signed_up, :as => :checkbox, :param_only => true %>
param_only is my made-up suggestion. It says 'this isn't even a transient property. Its just for this action.
class UserController < ActionController::Base
...
def create
if params[:tweet_when_signed_up] # haven't done this yet -- == 1 or !.nil?
Tweeter.tweet( ... )
end
#user = User.create( params[:user] )
end
The ability to do this is probably there -- does anyone know how to do effectively what I think is a good idea above?
thanks!
Instead I want to create a record
somewhere else (like a transaction)
that recorded the date/time they
accepted the T&Cs.
Use the attr_accessor that bensie describes to integrate the field with formtastic.
Formtastic is about view logic, while the relationship are more model logic. Don't worry about creating the related record in the form. Instead, use callbacks like before_update and after_save in the model to ensure the related record has been created.