How to get values from different table using association in rails? - ruby-on-rails

I've two tables in my Postgres database structures given below:
CREATE TABLE tables(
id serial NOT NULL,
name character varying(255),
table_state_id integer,
table_type integer,
CONSTRAINT tables_pkey PRIMARY KEY (id)
)
AND
CREATE TABLE table_states
(
id serial NOT NULL,
name character varying(255),
CONSTRAINT table_states_pkey PRIMARY KEY (id)
)
Table Model :
class Table < ActiveRecord::Base
attr_accessible :name, :table_type, :table_state_id,
belongs_to :table_state
end
TableState Model:
class TableState < ActiveRecord::Base
attr_accessible :name, :color_code
has_many :tables
end
In View I'm accessing like that:
= debug #table_data.table_state.name # Where `#table_data` is a variable from `tables` table
Through association I want to access name column of table_states table whose ID is present in table_state_id column of tables table. How can I do it?

You are having everything right in your code. There must be nil saved in your table_state_id in your tables table.
Error indicates that your table_state associated object is nil. this #table_data.table_state will return table_state object and error referring this to nil.
Try run select table_state_id from tables on your db console and see results. And make necessary changes in record through db console.
For future you can also use try to rescue such problem (specially production mode)
= debug #table_data.table_state.try(:name)

Related

How to update a table which doesn't have primary id column in rails

I am dealing with legacy code and do not have access to the database. There is a table which does not have a primary id column.
I can find a record using record = Model.find_or_initialize_by(listing_id: rating.pid, criteria_id: 33).
I can increment an attribute with record.rating_count += 1 but when I try to save it with record.save!, it gives the error TypeError: nil is not a symbol nor a string.
I think this is because record does not have a primary id (key) but I am not sure why it doesn't update the record.
If you have any suggestions, please let me know.
I also received the error TypeError: nil is not a symbol nor a string when trying to update a model which has no id column (or other primary key I could use). I had to add one.
You can add a primary key retrospectively using a migration:
add_column :people, :id, :primary_key

Defining table compound primary keys in rails for Cassandra

Given the following pseudo-cql table structure:
CREATE TABLE searches (
category text,
timestamp timestamp,
no_of_searches int,
avg_searches double,
PRIMARY KEY((category, timestamp), no_of_searches)
);
and the following Rails Cequel model:
class Search
include Cequel::Record
# Table columns
key :category, :text
key :timestamp, :timestamp
key :no_of_searches, :int
column :avg_searches, :double
end
when I try to synchronise the model using:
rake cequel:migrate
the following rake error is thrown:
rake aborted!
Cequel::InvalidSchemaMigration: Existing partition keys category,timestamp differ from specified partition keys timestamp
I'm trying to get the above rails model to synchronise with the above table using the partition keys, although it's stating that the two sets of keys are different. I've tried defining the keys in the same order, but has not worked.
My objective is to get the pre-defined database table with partition keys working with the rails model. Any help would be grateful!
The key method supports an options hash as a third parameter. The options hash adds further support to the defined key such as order and partitioning.
Based upon the given table definition it would mean your table columns would look something like this:
# Table columns
key :category, :text, { partition: true }
key :timestamp, :timestamp, { partition: true }
key :no_of_searches, :int
column :avg_searches, :double
Unfortunately this is not documented within the Cequel README, however it is documented within the code, for which can be found here.

added custom primary key, but still giving error for old default id column in the table

i have two relations for example example1 and example2
and example1 has_one example2
example2 belongs_to example1
example1
phone_number primary key
example2
phone_number foreign key
when i do this
Example1.create!({phone_number:"1231231231"})
and
u = User.find_by_phone_number("1231231231")
u.example2 = Example2.new(attributes)
it gives me error saying example1_id undefined column
and i have deleted activerecords default id columns to add my own primary key
can anyone please help me here
i think i am missing some trick for models association.
thanks.!!
Use:
belongs_to :example_1, :foreign_key => "phone_number"

Manually set value for primary key when saving data in rails

In my rails app, i am using a legacy database.
class Expression < ActiveRecord::Base
set_table_name "EXPRESSION"
set_primary_key "EXP_ID"
belongs_to :sub, :foreign_key => "EXP_SUB_FK"
end
To save an entry in the 'EXPRESSION' table, i am using the following code in my controller method:
#expression = Expression.create(
:EXP_ID => 7,
:EXP_SUB_FK => 99991886,
:EXP_STRENGTH => 'strong',
:EXP_ADDITIONAL_STRENGTH => 'intense',
:EXP_COMPONENT_ID => 43444
)
I have to manually set the EXP_ID each time i save an entry (i will get the id from another table), but the above code does not save the EXP_ID. All the other values are saved except for the EXP_ID.
If i comment out 'set_primary_key "EXP_ID"' in the Expression model, it works but i need to define EXP_ID as primary key.
Is there a way of allocating a value for a primary key when saving an entry to the dbase?
I would be grateful if anyone can provide me with some hint.
Set the EXP_ID in a before_save filter defined in the the Expression model.
UPDATE:
Added Sample:
before_save :set_exp_id
def set_exp_id
self.exp_id = 5555555
end

Activerecord, 'foregin_key' has to be a combination of 2 fields

I want a has_many relationship described below
class User < ActiveRecord::Base
has_many :mcollections, :foreign_key=>'obj_id'
end
Below is definition of table mcollections
create table mcollections (
id int not null auto_increment,
obj_id varchar(255) not null,
category varchar(255) not null,
);
The :foreign_key is NOT A SINGLE FIELD on table mcollections. Foreign key has to be a combination of 2 fields (obj_id + category). How can I specify this in User class?
I don't see the sense of using foreign keys here.
A foreign key should be the primary key of another table. Neither obj_id nor category could be used as foreign key because they are not part of the primary key.
Cant you do it another way?
Its not the best practice to use multi-column foreign keys in rails...

Resources