How to take value for Object result in ruby on rails - mysql

I want to print specific value from object result. here is i am execute SQL query and take all data from View tables, All data coming from "Employee_Information" view(table).
hr_controller.rb
class HrController < ApplicationController
def internal_employee_page
#employees = MysqlConnection.connection.select_all("SELECT * FROM Employee_Information")
end
end
internal_employee_page.html.erb this is my first view
<div id="job_details">
<% #employees.each do |emp| %>
<%= render partial: "hr/employee_details", locals: {emp: emp} %>
<% end %>
</div>
_employee_details.html.erb this is my second view
<h3> User Name : <%= emp%> </h3>
like this I am trying to print all value
then I got following result
I want to print each value
I tried this also in my second view
<h3> User Name : <%= emp.full_name%> </h3>
But I got Error:
Please help me I tried every thing according to my knowledge, where am I wrong and what is problems

Try this:
<h3> User Name : <%= emp["full_name"] %> </h3>

you are trying to read values from Hash,so emp.full_name will not work, you can read value from hash like Hash['key']
so for full_name do <%= emp['full_name'] %>

<h3> User Name : <%= emp.full_name%> </h3>
full_name is not an attribute of employee instance that's why you got this error. try fetch specific attribute which is present in that employee instance.

Right now your response objects are just simple Hash objects and to access the values for keys you would need to use Hash methods such as [] or fetch to retrieve the values. If you would like more method like syntax you could do one of the following:
Use ActiveRecord or another ORM mapper
Create Dynamic or Static classes yourself and map the results to them
Monkey Patch Hash with something like method_missing to fake this concept

Related

Rails_Admin - How to edit each key of a Jsonb as a field?

I have a jsonb attribute in my model, called config_params.
config_params: {key_a: 1, key_b: 100}
I need to edit it in rails_admin, but I need to edit each key as a different field.
key_a a field and key_b another, and if exists.
The question is because each config_param can hold different keys, it makes as if I need to know the object before building the fields and I can't only build virtual fields. It needs to do dynamic.
I created dynamic attributes on the model by singleton, it works fine! but I can't access the object in the building time of fields to get what config_params keys there are to build the fields.
I resolced it with singleton methods and one partial.
Into model I added calbacks to load attributes in run time:
after_initialize :load_configs
after_find :load_configs
And the load_configs method
def load_configs
config_params&.keys&.each do |param|
define_singleton_method(param) do
config_params[param]
end
define_singleton_method("#{param}=") do |value|
config_params[param] = value
end
end
end
OK! Now you have a jsonb field and into this there are many keys end each key has an attribute on instance method.
Exemple:
instance.config_params = {'key_a': 1, key_b: 2}
instance.save
instance.reload.key_a
1
instance.key_a = 10
instance.key_a
10
instance.key_b
2
OK! Model ok!
Now you need load it into admin, ok?
let´s go!
into a file that you config the rails_admin to your model put it
edit do
group 'Configurations' do
field :config_params do
partial 'config_params_partial'
end
end
end
Now you need create the partial file into de folder
app/views/rails_admin/main/_config_params_partial.html.erb
The partial code is like it
<% #object.config_params&.each do |key, value| %>
<%= form.fields_for :config_params, #object.config_params[key] do |config_params_fields| %>
<div class="field controls">
<%= config_params_fields.label #object.type.config_params[key]['label'] %>
<br/>
<%= config_params_fields.text_field key,
:value => value,
type: #object.type.config_params[key]['kind'],
disabled: #object.type.config_params[key]['editable'] == false,
class: 'form-control' %>
<% if #object.type.config_params[key]['required'] == true %>
<span class="help-block">Obrigatório. </span>
<% end %>
</div>
<% end %>
<% end %>
OBS: I created a model called type that control each meta-info about my fields, but you can create it locked, only fill field properties.
Restart server and be happy!

How to add the variables of array to database table

I have a form. Posting array variables from this form in the same name. (Sorry for my bad English.)
Here is the example:
<input type="text" name="name[]" class="form-control">
It is coming like ["a", "b", "c"]
I need save this variables to mysql from array. Not with array. Just one by one.
Create from my post controller
array_length = params[:type].size
for i in 0..array_lenth
type = params[:type][i]
name = params[:name][i]
title = params[:title][i]
value = params[:value][i]
#And save code.
end
I know i can save with some normal sql query but i dont know should i use or how i can use params require permit . something like
def form_params
params.require(:form).permit(:id, :type, :name, :value, :title, :post_id)
end
If i use this, how can i determine the necessary variables. Please help me and sorry for my English :)
Note: I have new post form and i have to add some variables to another table in post form (it is those arrays)
You have to specify that the param is an actual array, something like:
def form_params
params.require(:form).permit(:id, :type, :value, :title, :post_id, name: [:name_of_attribute, :another_name_for_attribute])
end
And then for your form:
<div class="field">
<%= form.text_field "name[name_for_attribute]" %>
</div>
Where the name_for_attribute is the name of the attribute you want it to be, so on the controller you will read the params like:
"form" => {"name"=>{"name_for_attribute"=>"The entered value"}
You can change the name_for_attribute for whatever you want and if for some reason someone tries to add another weird thing into the array by inspecting the HTML, you will filter all the attributes you want anyway.
Hope this helps! Let me know how it goes

Rails from a high-level view: performing calculations on a model value between view and controller

This must be a common need but I can't seem to find a definitive answer on the most rubyesque way. I need to create a fairly complex algorithm to dynamically calculate course grades in a rails 4.1 app.
Specifically, I have a model, "course", and whenever an instance of it is displayed in the view, I want to dynamically calculate the current grade (a decimal value, calculated from many course.field values) and display it as a letter value using a switch/case. My assumption was that I could do this in the controller (but it almost seems like it's complex enough to warrant it's own -- module? In C++ I would create a class). At the same time, since it is created dynamically, it seemed like bad form to create a current_grade field for it in the model, so it's not one I can pass back and forth as one of the allowable params (that I know of-- can one pass a variable in the params that is not represented in the db?).
In my initial research I see suggestions of hidden_field_tags and helper_methods and all_helpers and modules and global modules and more. Under time pressure, I dread beginning down the wrong path. Which is the better approach? Or a good high level doc for reference?
As an example, here is one view in which I would like to calculate current grade, compare it to desired grade, and display accordingly.
# index.html.erb
<% #courses.each do |course| %>
<li>
<%= my_algorithm_to_calculate_curr_grade(many course.fields used to caluculate)
<= course.desired_grade ? "set li to <Color: red>" : "set li to <Color: green>" %>
<%= course.course_name %>
Current Calculation: <%= display_results_of_previous_calculation %>
(Goal: <%= course.desired_grade %>)
<%= link_to 'Show', course %>
<%= link_to 'Edit', edit_course_path(course) %>
<%= link_to 'Drop Course Without Penalty', course, method: :delete, data: { confirm: 'Are you sure?' } %>
</li>
<% end %>
It's hard to tell from your question if course.fields are attributes of Course or different model(s). If all the fields are Course attributes, I would put it as an instance method on Course.
class Course < ActiveRecord::Base
def calculated_grade
# fun algorithm
end
end
If course.fields need to be loaded from the database, I'd probably go with a Plain Old Ruby Object (PORO), maybe call it CourseGradeCalculator (put it in app/models, why not? It's business logic)
class CourseGradeCalculator
attr_reader :course, :fields, :grade
def initialize(course, fields)
#course = course
#fields = fields
#grade = calculate_grade
end
private
def calculate_grade
# fun algorithm
end
end
# controller
#course = Course.preload(:fields).find(params[:id]
# view
CourseGradeCalculator.new(#course, #course.fields)

.collect method get an error undefined method `collect' for nil:NilClass

I'm trying to have a drop down list but when i try it it give me
undefined method `collect' for nil:NilClass
the controller:
def existing
#courses = Course.all
end
def duplicate
course = Course.find_by_id(permitd_up[:id])
new_course = course.dup
if new_course.save
redirect_to :action => 'show'
else
redirect_to :back
end
end
the view:
<h3>Choose a Course</h3>
<%= form_for :course , url: {:action => "duplicate" , method: "post"} do |f|%>
<%= f.select :id , #courses.collect{|c| [c.id , c.name]} %>
<br><br>
<%= f.submit%>
<%end%>
You will receive the following error
undefined method `collect' for nil:NilClass
on
<%= f.select :id , #courses.collect{|c| [c.id , c.name]} %>
Only when #courses instance variable was not set in the action that rendered this particular view.
I see that #courses variable is set in the existing method. If you are using existing as an action which renders this view then your view name must be existing.html.erb.
Or if you are rendering the view from a different action then in that case you should set #courses value in that particular action by either directly setting the value within action OR by calling existing method from there.
If you have your courses as a database table, you might want to try using rails' built in field helper collection_select. It will populate your select field with all of the data available in your model. If you want a drop-down like the one you are describing, I believe using collection select is the best way to handle it.
You can read up on it here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
Alternatively, if you have a ton of courses, maybe try looking into using a text field with autocomplete. Jquery UI has a plugin that makes this very easy. You can check out the railscasts for it here: http://railscasts.com/episodes/102-auto-complete-association-revised.
It requires a pro account but if you do a lot of rails developing it will be the best $9 you spend every month.
If you would like to continue to do it this way, make sure that you are defining
#courses = Courses(:all) in the correct controller action, otherwise you will have nothing to render.

Changing value of Ruby Variable in Html.erb

I have the following code in my controller:
class TestController < ApplicationController
##a = 1
def index
#temp = connection.execute("select test_id from mastertest limit #{##a}, 5;")
end
And I have the following code in my View(Html.erb) File:
<button type="submit" value="Next" form="submit_form">NEXT</button>
<form id="submit_form">
<% ##a = ##a + 1 %>
<table>
<% #temp.each do |row| %>
<tr><td><%= row[0] %></td></tr>
<% end %>
</table>
</form>
So basically I am trying to change the value of the class variable ##a on clicking the Next button. But it does not change the value of ##aa. Can someone help me how to do that.
Did you try using helper method?
module ApplicationHelper
##a = 1
def increment_a
##a = ##a + 1
end
end
and in your view just call;
<% increment_a %>
Not that the ## variable is a class variable and it's shared among all instances of the that class. So define that class somewhere in the ApplicationHelper class and then it will be shared and can be accessed in the Controllers and views.
In all cases I highly discourage using class variables in such a way and recommend that you ind another way to share data/variables between view / controller. Maybe use another supporting class or store values in the database.
If you want to alter a Rails variable on a form submission, you should put the code to do it in the action which processes the form.
As you've written it, I believe the variable will get set when the template containing the form is rendered.
I also vaguely recall that there's some special considerations about class variables in Rails apps. You should look into that and make sure you're using a technique that won't cause any unexpected results.
Ok I managed to fix this:
Ruby has something called a global variable which can be declared like this :
$a = 1
Using $a everywhere retains its value in the controller and the view as well.