Rails: Show data from 2 tables in "collection_select" - sql

I have two models:
class Category < ActiveRecord::Base
attr_accessible :active, :title, :url_name
has_many :category_images
end
class CategoryColor < ActiveRecord::Base
belongs_to :category
end
In the categories table is a list of categories, in category_colors is list of added colors for a category.
I want to display in the collection_select all categories, that have in the table category_colors some colors. How to do that?
So far, I am able to only list all categories in the select tag:
= collection_select(:item, :chosen_category, Category.order('categories.title ASC'), :id, :title, prompt: true)
Thank you very much for an advice

I've achieve that this way:
= collection_select(:item, :chosen_category, #category_colors.map(&:category), :id, :title, prompt: true)
and in the controller for this action:
#category_colors = CategoryColor.group('category_id')
Voila!

Hope this helps
<%= collection_select(:categorycolor, :categoty_id, Category.order('categories.title ASC'), :id, :title, prompt: true) %>

Related

How to use "accepts_nested_attributes_for" in rails 3?

I'm following the docs and toying with simple_form, formtastic, and nested_form gems with no success. This very simple example yields empty for for me:
resort.rb
class Resort < ActiveRecord::Base
attr_accessible :address, :description, :latitude, :longitude, :name, :phone, :second_name,
:resort_type_id, :infrastructure_attributes
validates_presence_of :name, :address, :phone, :description
has_many :infrastructures
belongs_to :resort_type
accepts_nested_attributes_for :infrastructures
end
infrastructure.rb
class Infrastructure < ActiveRecord::Base
attr_accessible :name, :description, :infrastructure_type_id, :resort_id
belongs_to :resort
belongs_to :infrastructure_type
end
form view
= form_for #resort do |f|
= f.fields_for :infrastructures do |i|
= i.text_field :name
Seems I missed something obvious but can't figure out what exactly is wrong with the code.
If I may ask, in your controller action did you build the appropriate code for your infrastructure. Something like
3.times { #resort = #resort.infrastrucures.build }
To my knowledge you need something like this for your form before it can build the proper nested form content

Form not displayed correctly

i have a form consists of the following models
Employee.rb
class Employee < ActiveRecord::Base
attr_accessible :employee_number, :joining_date, :first_name, :middle_name, :last_name,
:gender, :job_title, :employee_department_id, :qualification, :experience_detail,
:experience_year, :experience_month, :status_description, :date_of_birth, :marital_status,
:children_count, :father_name, :mother_name, :husband_name, :blood_group, :nationality_id,
:home_address_line1, :home_address_line2, :home_city, :home_state, :home_pin_code,
:office_address_line1, :office_address_line2, :office_city, :office_state, :office_pin_code,
:office_phone1, :office_phone2, :mobile_phone, :home_phone, :email, :fax, :user_id,
:reporting_manager_id, :employee_grade_id, :office_country_id,
:home_country_id, :employee_category, :employee_position_id
belongs_to :employee_department
has_many :counselor_supervisors
belongs_to :employee_position
def to_label
full_name = first_name + " " + last_name
end
end
EmployeeDepartment.rb
class EmployeeDepartment < ActiveRecord::Base
attr_accessible :code, :name
has_many :employees
has_many :employee_positions
has_many :counselor_supervisors
has_many :batch_leadership_supervisors
def to_label
name
end
end
CounselorSupervisor.rb
class CounselorSupervisor < ActiveRecord::Base
attr_accessible :employee_id, :employee_department_id, :employee_position_id
belongs_to :employee
belongs_to :employee_department
has_many :batch_counselor_supervisors
def to_label
employee.to_label
end
end
BatchCounselorSupervisor.rb
class BatchCounselorSupervisor < ActiveRecord::Base
attr_accessible :counselor_supervisor_id , :employee_department_id , :counselor_batch_id,
:batch_counselor_advisors_attributes
has_many :batch_counselor_advisors
belongs_to :counselor_supervisor
belongs_to :employee_department
belongs_to :counselor_batch
accepts_nested_attributes_for :batch_counselor_advisors
end
Employee_position.rb
class EmployeePosition < ActiveRecord::Base
attr_accessible :position_title, :employee_department_id
has_many :employees
belongs_to :employee_department
def to_label
position_title
end
end
batch_counselor_supervisors/new.html.erb (part of the form which related to my question)
<%= simple_form_for(#batch_counselor_supervisor) do |f| %>
<%= f.error_messages %>
<%= f.association :employee_department, as: :select %>
<%= f.input :counselor_supervisor_id , collection: EmployeeDepartment.all, as: :grouped_select, group_method: :counselor_supervisors %>
<% end %>
the dropdown list appears like this:
If I added an employee which belongs to the first department "Business Administration", the form will be displayed correctly like this:
Update: after adding label_method: :to_label, so my form became like this :
<%= simple_form_for(#batch_counselor_supervisor) do |f| %>
<%= f.error_messages %>
<%= f.association :employee_department, as: :select %>
<%= f.input :counselor_supervisor_id ,
collection: EmployeeDepartment.all, as: :grouped_select, group_method: :counselor_supervisors, label_method: :to_label %>
<% end %>
the employee name displayed correctly but still the department name not displayed correctly as the following image:
Is this SQLite3 issue ? and What can I do in order to solve this if it sqlite3 issue or not.
From what I see, you only have an issue with the labels not being displayed correctly. Could you try to explicitly set the method on your input:
label_method: :to_label
For more information have a look at https://github.com/plataformatec/simple_form and search for *label_method*
What are the actual relevant rows in your Employee table and your EmployeePosition table?
In your Employee table you happen to have these 2 columns;
employee_position_id
employee_position.
Since employee_position is also a table name, it's bad/reduntant model structure which might be confusing your include method of the query. It's possible that in your tables, the rows are fully filled out to complete the first query, but not for any of your other queries even though you think it is.

Passing value from one model to another using a drop-down menu

Models:
product.rb:
class Product < ActiveRecord::Base
attr_accessible :cat_id, :id, :name
belongs_to :category
end
category.rb:
class Category < ActiveRecord::Base
attr_accessible :id, :name
has_many :products
end
Routes:
routes.rb
resources :categories do
resources :products
end
I want to add products to category. What to write in controller and view of product please help!
Please!! I am a beginner to rails!
If you want a drop-down menu:
In _file.html.haml
= label_tag :Category
= select_tag "product[category_id]", options_from_collection_for_select(#categories, :id,:name,#selected = #product[:category_id] :include_blank => true
In products_controller.rb:
before_filter :get_categories, :only => [:new,:edit]
def get_categories
#categories = Category.all
end
You can do as shown below,
If your path(url) should be like http://loaclhost:3000/category/1/produts, use id params from your url
Pass cateogry id into product view
form.erb
<%= f.hidden_field :cat_id , :value => <pass catogory id from routes url> %>
then follow usual create method ( Please inspect object whether cat_id created or not )
Now , you can access category value from cat_id of product.
Hope it will be useful.

Rails, get object association when using build (object still not in database), the DRY

Im building a report system which uses a sort of meta question model. Questions are previusly saved in the database, and then depending of the type of report some questions are taken from the database.
Wanting to keep things DRY, i'm trying to figure out a way to pass the information of the Variable model to my report_header with no avail.
In the new action i have:
reportBody = #report_head.report_bodies.build(:variable_id => a.id)
#report_head.variables #modified, thx.
all i need is to pass the attributes from the Variable to report_head in a DRY way.
If you need to know my models:
class Variable < ActiveRecord::Base
attr_accessible :id,:break_point, :description, :name, :time_frequency, :v_type
has_many :report_bodies
has_many :report_heads, :through => :report_bodies
end
class ReportHead < ActiveRecord::Base
attr_accessible :email, :name , :report_bodies_attributes, :report_bodies, :variables_attributes
has_many :report_bodies
has_many :variables, :through => :report_bodies
accepts_nested_attributes_for :report_bodies
end
class ReportBody < ActiveRecord::Base
attr_accessible :report_head_id, :variable_value, :variable_id, :variables_attributes, :report_heads
belongs_to :report_head
belongs_to :variable
end
Update
I updated the model as suggested, and modified the way to call the variables. However im still confused about how to use it in the view, if i do something like:
<%= f.fields_for :variables do |variable| %>
<%= variable.text_field :name, :value => :name, :class => 'text_field' %>
<% end %>
it prints a string instead of the actual name.
You have define wrong name association, your association of ReportBody should be:
belongs_to :report_head
belongs_to :variable
This is not correct:
#report_head.report_bodies.build(:variable_id => a.id,:report_head_id =>#report_head.id)
chang it to:
#report_head.variables.build(:variable_id => a.id)
it's better, you don't have to set report_head_id. And this is wrong:
#report_head.report_bodies.variables
If you want to get all variables belong to #report_head, you just need using:
#report_head.variables

Rails 3 - Fields_for Nested attributes not showing on form

OK this is weird, I have basically the following classes:
class PriceProfile < ActiveRecord::Base
has_many :prices
has_many :price_profile_date_ranges
attr_accessible :name, :price_profile_date_ranges_attributes
accepts_nested_attributes_for :price_profile_date_ranges
}
class PriceProfileDateRange < ActiveRecord::Base
attr_accessible :end_date, :price_profile_id, :start_date, :prices, :prices_attributes
has_many :prices, :dependent=>:destroy
belongs_to :price_profile
accepts_nested_attributes_for :prices
}
class Price < ActiveRecord::Base
attr_accessible :price_profile_date_range_id, :price_profile_id, :product_id, :value
belongs_to :price_profile
belongs_to :price_profile_date_range
belongs_to :product
}
A price profile defines a pricing scheme for a particular product whose price changes over time. The date ranges over which a price is applied is stored in the price_profile_date_range table and finally the prices table holds all the prices. I'm using the following controller & view to create the form here for setting prices while creating a date range. Basically the form has a start and end date fields and a grid i.e it would have a list of texteboxs against all products to enter the price.
This is the view:
.row
.span9
= simple_form_for(#price_profile_date_range, :class=>'well') do |f|
.form-inputs
= f.input :start_date, :required => true, :as => :string, :input_html =>{:class=>'datepicker'}
= f.input :end_date, :required => true, :as => :string, :input_html =>{:class=>'datepicker'}
= f.input :price_profile_id, :as=>:hidden
%table.table.table-bordered.table-condensed.table-striped
%tr
%td
- #products.each do |product|
%td
=product[:name]
%td
- f.fields_for(:prices) do |price_element|
= price_element.input :value, :class=>'span1'
= price_element.input :price_profile_id, :as=>:hidden
= price_element.input :price_profile_date_range_id, :as=>:hidden
= price_element.input :product_id, :as=>:hidden
.form-actions
= f.button :submit
This isnt exactly the final form - the problem is that the f.fields_for line doesn't seem to execute. In the controller I initialise the #price_profile_date_range object with a set of prices. If I do a raise inspect it shows all the price objects even in the view however the fields_for doesn't execute at all. I'm pretty stuck here real badly.
Try changing the - to a = - sounds silly but maybe that's the problem.