简体   繁体   中英

Create a field in ruby not associated with a model

I am wondering how can i create a field not associated to the models, the only reason i need the field is to determine which actions to do on it.

Lets say i have a model article, and when creating a new article, i would like a hidden field that would have 0,1,2 and in the controller new, i would see if the params is equal to 0, then do this set of logic or 1 then this set of logic.

Thank you, I also know that defining a set of action for each action won't work.

In a form you can declare both hidden and visible fields that are not directly associated with your models. When you submit the form, in the form's action you can manipulate the attributes in the params that are not related to the model.

When you declare form fields you can use those that end with _tag like email_field_tag , radio_button_tag , and regarding your question, hidden_field_tag . Example:

<% hidden_field_tag 'this_is_hidden' %>

Try it out and inspect what comes into the action: raise params.inspect . In doing so you'll notice the params now includes keys for the attributes you declared that are not related to your model (like the attribute :this_is_hidden )

Try doing it with a hidden_field_tag. (recommendation: put it just before the submit button inside the form tag.)

http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-hidden_field_tag

hidden_field_tag 'decide', '0'

Then in the new action of the controller you can catch it inside the params hash, and compare it with params[:decide].to_i

most easiest way is to have a hidden field as @Zippie, mentioned. However it has some risks as end user could modify the value in the hidden field and your program could behave differently.

What i personally believe is to have a some kind of a methodology to identify from the passing parameters

Ex: if it is a new object then it should go to method A etc... 

By that way end use will not have a chance to modify the workflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM