How to select columns from active record? - ruby-on-rails

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.

Related

One form input to set two database values

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.

Rails - getting ID of currently created element with formobject

I would like to know how can i get ID of currently created Model record, which was saved by Form Object. I have:
#object_form.save
id = #parent.objects.last.id
i would like to change it into something more meaningful like:\
#object_form.save
id = (currently saved OBJECT.id)
If you're saving the object, and if that save is successful, you'll be able to just reference the id of the newly saved object:
id = #object_form.id if #object_form.save
You have to remember that you're not saving the "form", but an ActiveRecord object. Thus, if you've still got the #instance_variable available from the save, it will return the newly populated id method.

Getting params from URL in model's create method

Is there a way to get the params from URL in the create method?
My URL for the "new" view is:
/model_name/new?other_model_id=100
I would like to be able to alter the model with ID 100 when I create a new model. I've tried calling params[:other_model_id] in my "create" method, which returned nil and I tried setting the following variable in my "new" method:
#other_model = Model.find(params[:other_model_id])
I have a field called "other_versions" in my model, which is an array of model IDs. When I create a new model I want to add the new model's ID to the array of model IDs in the old model.
Why don't you use the after_createfilter (http://guides.rubyonrails.org/active_record_callbacks.html) and just add the "other_model" id on an hidden field on your create/edit form?
Please make sure, if you are using Rails >4, to add that parameter on your strong parameters (http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html) otherwise it will always be empty when you check on params.

Changing the ID of a new object in Rails

So I have a Customer model in my Rails app and whenever a new customer is created I am getting a number as input from the user and I want that number to become the id of the customer on my database instead of the default 1, 2, 3, and so on. Is it possible to do that? If so, how?
EDIT: Let me be a more clear about what I want: I have a Customer and A Brand model. A customer has_many brands and a brand belongs_to a customer. Whenever the user creates a new brand, I want to connect it to its customer using that number that the user entered for the customer. Right now, whenever the user creates a new brand, I ask him to enter the customer_id value to connect the brand to a customer, but that is the id number generated by Rails. How do I make that customer_id attribute refer to the specific number the user entered for a customer, instead of the customer id generated by Rails.
It's possible, but don't do that. Just allow Rails to manage the auto-generated ID itself, and add this number - whatever it is - as a separate attribute in your model and saved to a separate field in your database.
As smathy mentioned, you can do the following:
1.First, generate a migration that add your custom attribute
rails g migration AddCustomerIdToCustomers customer_id:integer
2.When user enter the id, you would want to do something like this:
#customer.customer_id=params[:customer_id]
#customer.save
3.Then you can retrieve the custom object as
#customer = Customer.find_by_customer_id(customer_id)
where customer_id is the id you want.
As the above answer suggests, it is better let Rails handle the id attribute, because it is used extensively in Rails to handle database relationships ActiveRecord queries, etc. You do not want the extra headache of modifying it yourself.

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

Resources