Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attr_accessor use table name

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 the field_name but with my association i have many table with the same field name.

For exemple

class User < ActiveRecord::Base
    has_one :agent
    has_one :language
    attr_accessor :code
end

But i have a field :code in agent table and in language table. I'm trying to find a solution on internet but without success

Is there a way to specify the table name ?

like image 274
Gregory Frerot Avatar asked Sep 13 '26 02:09

Gregory Frerot


1 Answers

You can use these way to get model speicific code from 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:

Now you can access it User.first.agent_code for agent model Also you can access it User.first.language_code for language model

You can access the specific code by specific model wise

like image 99
Rajarshi Das Avatar answered Sep 14 '26 14:09

Rajarshi Das