Rails tiene muchos con nombre de alias
En mi modelo de usuario podría tener:
has_many :tasks
Y en mi modelo de tarea:
belongs_to :user
Entonces, suponiendo que la clave foránea 'user_id' se almacenara en la tabla de tareas, podría usar:
@user.tasks
Mi pregunta es, ¿cómo declaro la relación has_many de tal manera que pueda referirme a las Tareas de un Usuario como:
@user.jobs
... o ...
@user.foobars
Muchas gracias.
167
Author: doctororange, 2009-07-22
3 answers
Dale una oportunidad a esto:
has_many :jobs, foreign_key: "user_id", class_name: "Task"
Tenga en cuenta que :as
se utiliza para asociaciones polimórficas.
320
Author: Sam Saffron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 07:17:16
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 07:17:16
También puedes usar alias_attribute
si todavía quieres poder referirte a ellas como tareas también:
class User < ActiveRecord::Base
alias_attribute :jobs, :tasks
has_many :tasks
end
32
Author: Pwnrar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-03 22:08:30
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-03 22:08:30
Puedes hacer esto de dos maneras diferentes. Uno es mediante el uso de "como"
has_many :tasks, :as => :jobs
O
def jobs
self.tasks
end
Obviamente el primero sería la mejor manera de manejarlo.
-54
Author: Brent Kirby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-22 05:00:38
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-22 05:00:38