How to write a ruby code that add a new user's data to a user_custom_fields

(SMHassanAlavi) #1

I am not familiar with rails so much and I want to code a plugin that asks user his job and fill the job’s user_custom_fields(already created manually) in the database.

Because I’m familiar with PHP, I add new rows to database directly by SQL Queries (Like what we do in PHP) But this won’t increase the sequence table and this may cause some damages to site.

I have tried to increase the sequence table but postgres didn’t allow me to change data in _seq tables.

I have two solution:

1-get the permission to edit rows in _seq tables and change them with SQL Query.

2-edit or add the database using rails methods.(that increase the _seq tables automatically)

Surely, the second solution is the best but this solution is good for who are familiar with rails and MVC and for me and as a temporary solution(to avoid big harms) the first solution is good until I learn how to code with Rails.

So how Can I solve this problem? What is your Idea?

(Jay Pfaffman) #2

Is there a reason not to use the built-in custom user fields?

(SMHassanAlavi) #3

I am exactly using them. I have created a custom user field in admin panel.

The problem is adding a string to that custom user field.

(SMHassanAlavi) #4

I find the answer.

Adding a new row or editing older rows in Ruby On Rails isn’t like PHP because Rails is so much objective even when you want to work with database.

I will explain my answer for other who have my problem:

FORGET about sql query, in Here everything are objects, every row in database is an object. for adding a new row, you should create a new object and if you want to edit a row, you should find that row as an object.

So if everything is object here, What is the class name for creating new one?
If you want to edit the user_custom_fields table, the class name is UserCustomField.
to edit an exiting data, you should find it first like this:

MyObject = UserCustomField.where(name: "user_field_5", user_id: 364).first
MyObject.value = "new Value"

this code will change the custom_user_field with name user_field_5 and user_id 364 .
now for adding new one you should do this:

NewObject = UserCustomField.create(user_id: 634, name: 'user_field_6', value: 'my value')
this code will create a new row in database and you shouldn’t define id, created_at , updated_at because rails will define them automatically and also increase the sequence. :wink: