ActiveScaffold - changing default name of associated object - ruby-on-rails

My model "combobox" has_many "comboboxselects", and "comboboxselects" belongs_to "combobox". Activescaffold of "comboboxes" displays data in comboboxselects-column like "#<Comboboxselect:0x472d25c>". How to make display the "answer" column from table "comboxselects"?
Models:
class Combobox < ActiveRecord::Base
has_many :comboboxselects
end
class Comboboxselect < ActiveRecord::Base
belongs_to :combobox
end
Schema:
create_table "comboboxes", :force => true do |t|
t.string "question"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "comboboxselects", :force => true do |t|
t.integer "combobox_id"
t.string "answer"
t.datetime "created_at"
t.datetime "updated_at"
end
Output:
class ComboboxesController < ApplicationController
active_scaffold :combobox do |config|
config.list.columns = [:id, :question]
config.columns = [:question, :comboboxselects]
end
end
class ComboboxselectsController < ApplicationController
active_scaffold :comboboxselect do |config|
config.list.columns = [:id, :combobox, :answer]
config.columns = [:answer]
end
end

First, all fields referenced in config.list.columns have to be included in config.columns (any explicitly-defined config.*.columns fields must be subsets of config.columns).
Then, in each model that does not already have a name or title field or method, you have to declare this custom method:
class Comboboxselect < ActiveRecord::Base
belongs_to :combobox
def to_label
"#{answer}"
end
end
See ActiveScaffold documentation: Describing Records: to_label

When you say displays I assume you mean in a view? Can you post the code your running to get that output.
Looks to me like you just have Comboboxselect object, have you tried adding .answer to it to access the attribute you want?

Related

How To add new table and link it with previous table in with adding index in ruby

I have this table structure:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :encrypted_password
t.string :salt
t.timestamps
end
end
end
And I want to add a new table as shown below:
class CreateHolidays < ActiveRecord::Migration
def change
create_table :holidays do |t|
t.string :earn_leave
t.string :seek_leave
t.string :unplanned_leave
t.timestamps
t.timestamps
end
add_index(users,id)
end
end
What should I do for this, please also suggest commands that can/should be used for migration.
You want to look up about foreign_keys:
#app/models/holiday.rb
class Holiday < ActiveRecord::Base
belongs_to :user
end
#app/models/user.rb
class User < ActiveRecord::Base
has_many :holidays
end
This will mean you have to add the user_id foreign key to your holidays data table:
class CreateHolidays < ActiveRecord::Migration
def change
create_table :holidays do |t|
t.references :user
t.string :earn_leave
t.string :seek_leave
t.string :unplanned_leave
t.timestamps
t.timestamps
end
end
end
You must remember that Rails is designed to be built on top of a relational database. As such, it uses foreign_keys in the tables to locate associated records:
The above will allow you to call:
#user.holidays
and
#holiday.user

Inheritance with ActiveRecord at the same time

I have a class 'Report' that has columns 'description', 'pending', etc.
/app/models/report.rb
class Report < ActiveRecord::Base
end
class CreateReports < ActiveRecord::Migration
def change
create_table :reports do |t|
t.boolean :pending, :default => true
t.boolean :accepted, :default => false
t.text :description
t.timestamps null: false
end
end
end
But I also have two other classes: ReportPost (when a User report a Post), and ReportTopic (when a User report a Topic). I used this approach because I can user 'belongs_to :topic' for ReportTopic and 'belongs_to :post' for ReportPost. So, here comes the problem:
Since ReportPost and ReportTopic have the same columns of 'Report', I need to use the inheritance from 'Report'. But I also need to use ActiveRecord inheritance to capture new attributes from :report_topic migrates.
But, how?
Here are the other classes:
class ReportTopic < Report
belongs_to :topic
end
class ReportPost < Report
belongs_to :post
end
`And, the migrates:
class CreateReportPosts < ActiveRecord::Migration
def change
create_table :report_posts do |t|
t.belongs_to :post
t.timestamps null: false
end
end
end
class CreateReportTopics < ActiveRecord::Migration
def change
create_table :report_topics do |t|
t.belongs_to :topic
t.timestamps null: false
end
end
end
You could use Single Table Inheritance (STI) in this case. Just add a column named 'type' to your report table.
def change
create_table :reports do |t|
t.boolean :pending, :default => true
t.boolean :accepted, :default => false
t.text :description
t.string :type
t.timestamps null: false
end
end
Rails will understand this as STI. Any subclass that you may create will have its type equal to the name of the class (e.g. type = 'ReportTopic')

Active Record how to add records to has_many :through association in rails

I have quite the Problem with my has_many :through association.
The models look like this:
class User < ActiveRecord::Base
has_many :roles
has_many :datasets, through: :roles
has_secure_password
end
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :dataset
end
class Dataset < ActiveRecord::Base
has_many :roles
has_many :users, through: :roles
end
I want to add a record to roles every time a new Dataset is created. It should
be created with the new Dataset, an existing User 'Admin' and the column name of Role should be set to 'Admin'.
I tried everything I found on Stackoverflow but nothing works for me.
My create method in the DatasetController looks this:
def create
#dataset = Dataset.new(dataset_params)
#dataset.save
#user = User.find_by(name: 'Admin')
#dataset.users << #user
##dataset.roles.create(user: #user, dataset: #dataset, name: 'Admin')
respond_with(#dataset)
end
I tried both the << operator and the create method.
the first results in:
ActiveRecord::UnknownAttributeError in DatasetsController#create
unknown attribute: dataset_id
the second in:
ActiveModel::MissingAttributeError in DatasetsController#create
can't write unknown attribute `user_id
Does anyone know why I get these errors?
my schema.rb:
create_table "datasets", force: true do |t|
t.string "name"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "name"
t.string "mail"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
end
Your Role model needs columns to refer to which User and Dataset it belongs. Without these it has no idea who belongs to who.
So you simply need to create a migration to add these columns:
class AddRefererColumnsToRole < ActiveRecord::Migration
def change
add_column :roles, :user_id, :integer
add_column :roles, :dataset_id, :integer
end
end

ActiveRecord: find appropriate translation

I have models:
Category:
class Category < ActiveRecord::Base
has_many :entities, as: :resourcable
end
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.text :short_descr
t.text :full_descr
t.timestamps
end
end
end
Language:
class Language < ActiveRecord::Base
has_many :entities, as: :resourcable, dependent: :destroy
validates :code, uniqueness: true
end
class CreateLanguages < ActiveRecord::Migration
def change
create_table :languages do |t|
t.string :name
t.string :code
t.timestamps
end
end
end
And Entity:
class Entity < ActiveRecord::Base
belongs_to :language
belongs_to :resourcable, polymorphic: true
end
class CreateEntities < ActiveRecord::Migration
def change
create_table :entities do |t|
t.integer :language_id
t.string :name
t.text :short_descr
t.text :full_descr
t.references :resourcable, polymorphic: true
t.timestamps
end
end
end
In Categories there are default values for fields (short_descr, full_descr), In Entities there are translations for this fields. I need to render as json all Categories with appropriate translations: at first, I need to take Language with appropriate code (for example ru), next, I need to find all language Entities for this language, next, if Entity have filled short_descr and full_descr I need to render Category with this values, else I need to render the Category with default values (this values in Categories table). How to do this? I prefer ActiveRecord buy consider pure SQL.
EDITED
Now I'm trying to use gem 'squeel':
Language.joins{entities.category}.
select{coalesce(entities.short_descr, categories.short_descr)}.
where{languages.code == 'en'}
but it doesn't work (undefined methodshort_descr' for nil:NilClass`). There is the problem?
Entity.joins(:language, :category).
select('categories.*, coalesce(entities.short_descr, categories.short_descr) as short_descr,
coalesce(entities.full_descr, categories.full_descr) as full_descr').
where('languages.code = ?', 'en')

Rails 2: joint multi table

Sorry, i'am newbie
I have database:
Migrate
-Mst_group tble
class CreateMstGroups < ActiveRecord::Migration
def self.up
create_table :mst_groups do |t|
t.string :group_name
end
end
end
-Mst_japan
class CreateMstJapans < ActiveRecord::Migration
def self.up
create_table :mst_japans do |t|
t.string :name_level
end
end
end
-Tbl_user
class CreateTblUsers < ActiveRecord::Migration
def self.up
create_table :tbl_users do |t|
t.string :login_name, :null =>false,:limit =>15
t.string :password,:null =>false,:limit =>50
t.string :full_name,:null =>false
t.string :full_name_kana
t.string :email,:null =>false
t.string :tel,:null =>false,:limit =>15
t.date :birthday,:null =>false
t.references :mst_groups
end
end
end
-Tbl_detail_user_japan
class CreateTblDetailUserJapans < ActiveRecord::Migration
def self.up
create_table :tbl_detail_user_japans do |t|
t.date :start_date
t.date :end_date
t.integer :total
t.references :tbl_users
t.references :mst_japans
end
end
end
Model
class MstGroup < ActiveRecord::Base
has_many :tbl_users
end
class MstJapan < ActiveRecord::Base
has_many :tbl_detail_user_japans
end
class TblUser < ActiveRecord::Base
belongs_to :mst_group
has_one :tbl_detail_user_japan
end
class TblDetailUserJapan < ActiveRecord::Base
belongs_to :tbl_user
belongs_to :mst_japan
end
Controller
def index
#user= ???????
end
How to write command select : login_name, full_name, full_name_kana, email, tel, group_name, name_lever, start_date, end_date, total in controller
It depends on how you want to retrieve the User object. You need to tell Rails how to find the TblUser object. If, for example, the user ID is known, let's say in a variable called 'id' then you would do:
def index
#user=TblUser.find(id)
end
It depends on your application logic how Rails would know which user you need. You may need an input from the user in case of log in, etc.
(Typically in Rails you would call the table 'Users', by convention tables and classes have the same name and then you wouldn't need to call the class TblUser)
That is all you need in the controller, you don't need to tell it which fields you want.
Then in the View you can access all the fields:
Fields on TblUser, example:
<%= #user.email %>
You can access the fields from related objects through the relations, example:
<%= #user.mst_group.group_name %>
Hope that helps to get you started.

Resources