Usage table name Attr_accessor
Hi i have a problem with "attr_accessor" in rails 4
I have a model with many associations and when I use attr_accessor I put field_name, but with my association I have many tables with the same field name.
For example,
class User < ActiveRecord::Base
has_one :agent
has_one :language
attr_accessor :code
end
But I have a field: code in statement table and in language table. I am trying to find a solution on the internet but with no success
Is there a way to specify the name of the table?
source to share
You can use this way to get the code
model of the user
model
class User < ActiveRecord::Base
has_one :agent
has_one :language
delegate :code, to: :agent, prefix: true, allow_nil: true
delegate :code, to: :language, prefix: true, allow_nil: true
end
As an example:
You can now access it User.first.agent_code
for the model agent
Also you can access it User.first.language_code
for language
model
You can access specific code
with specific model
source to share