One form input to set two database values - ruby-on-rails

I have a form which when submitted creates a new record in a database. I have two values in the database, value_1 & value_2. In the form there is an input field for value_1 which is a dropdown value of yes and no. When the form is submitted I wish to have value_1 and value_2 set to the value selected in the input field for value_1. So if dropdown for value_1 is set to yes then value_2 is also set to yes.
I am currently using the following but believe there must be a more elegant solution:
params[:person][:free] = params[:person][:trial]
#person = Person.new(params[:person])
#person.update_attribute(:free, params[:person][:free])

First you should think about what you really want. What is your logic.
Do you want value_2 always equal to value_1? I hope not, because in this case u absolutely no need a second column in your database.
Do you want value_2 equal to value_1 only the creation of a new record but allow it to be edited after that? In this case you should put the logic in your model with a callback :
In your model add :
before_create :set_value_2
private
def set_value_2
self.value_2 = value_1
end
The private statement is because you don't want anybody to access the method outside the model itself.

Related

How to select columns from active record?

Using Devise to set the current user and current company,
I have an active record of User which contains certain fields that should not be exposed in some cases like password etc.
#<User email:*** password:***>
How can we select only selected attributes and keep them as active record object only.
output should be
#<User email:****>
current_user is getting created from devise helper.
In Active Record, you can use the select method to choose the attributes you want to retrieve from the database. Here's an example:
current_user.select(:email)
This will return a new Active Record object with only the email attribute populated, while keeping the other attributes as nil.
Note that select returns a new instance of the Active Record object and does not modify the original object. To persist the changes, you need to assign the result to a new variable or update the original object:
selected_user = current_user.select(:email)
Alternatively, you can use the attributes method to retrieve a hash of attribute names and values, and then select only the desired attributes:
attributes = current_user.attributes.slice("email")
selected_user = User.new(attributes)
This will give you a new instance of the User model with only the selected attributes.

How to set initial value for read only field

I have a django application which is using django.contrib.admin for administrative tasks.
For one model I now need to add a field which indicates which part of the code each row was created from. I am using readonly_fields to prevent this value from being changed through the administration interface.
A default value in this field will tell me that the row was either
created before the field was introduced
created by code which has not been updated to set the field
created through the administration interface
But I need better granularity than that. In particular I want to be able to distinguish between a row created by code which doesn't know about the field, and a row created through the administration interface.
Is there some way my ModelAdmin class can specify an initial value for a field mentioned in readonly_fields?
One way to do this is,
def get_form(self, request, caja=None, **kwargs):
self.form = YourModelForm
form = super(YourModelAdmin, self).get_form(request, caja, **kwargs)
form.base_fields['field'].initial = your_initial_data
return form
I found this solution, which appears to work:
class Admin(ModelAdmin):
readonly_fields = ('created_by',)
def save_form(self, request, form, change):
r = super(Admin, self).save_form(request, form, change)
if not change:
assert r.created_by == CREATED_BY_UNKNOWN
r.created_by = CREATED_BY_ADMIN
return r
CREATED_BY_UNKNOWN and CREATED_BY_ADMIN are values defined elsewhere in my code.

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.

How to Save page as Draft

I Had created a detailed form in Django having some mandatory fields .I want to save page as Draft option without exception if mandatory fields are not set that time. How can I do it?
First set required=False for the fields that don't have to be set if you save as a draft. Then, to your form, add a field like 'save_as_draft' which is a boolean. Now you need a method to validate these fields depending on the state of save_as_draft field (whether user checked this field or not). You can use such a method:
def is_provided(self, field):
value = self.cleaned_data.get(field, None)
if value == None or value == '':
self._errors[field] = ErrorList([u'This field is required.'])
if field in self.cleaned_data:
del self.cleaned_data[field]
Add this method to your form and use it in form's clean method to validate your fields. This would look like this:
def clean(self):
draft = self.cleaned_data.get('save_as_draft', False)
if not draft:
# User doesn't save a draft so we need to check if required fields are provided
req_fields = ['field1', 'field2', 'field3']
for f in req_field:
self.is_provided(f)
return self.cleaned_data
If user prefer save_as_draft button instead of checkbox, then you would need to modify your view and pass some parameter to your form's constructor depending on whether user clicked save_as_draft button or just save button. In Form constructor save this state aa self.save_as_draft and use this in Form.clean method to check if you are saving draft or not.
Greetings,
Lukasz

Add empty value to a DropDownList in ASP.net MVC

I'm building a data entry interface and have successfully bound the columns that have reference tables for their data using DropDownList so the user selects from the pre-configured values.
My problem now is that I don't want the first value to be selected by default, I need to force the user to select a value from the list to avoid errors where they didn't pick that field and by default a value was assigned.
Is there a more elegant way of doing this than to add code to include an empty value at the top of the list after I get it from the database and before i pass it to the SelectList constructor in my controller class?
The Html helper function takes a 'first empty value' parameter as the third argument.
<%=Html.DropDownList("name",dataSource,"-please select item-")%>
You can also use this way:
dropdownlist.DataTextField = ds.Tables[0].Columns[0].Caption;
dropdownlist.DataValueField = ds.Tables[0].Columns[1].Caption;
dropdownlist.DataSource = ds;
dropdownlist.DataBind();
dropdownlist.Items.Insert(0, new ListItem("Select ...", string.Empty));

Resources