【发布时间】:2023-04-01 02:23:01
【问题描述】:
这似乎是一个简单的问题,但对我来说有点困惑。我想找到一个处理这个问题的好方法。 我有5个模型。
工作
class Job < ActiveRecord::Base
has_many :job_entries_jobs
has_many :job_entries, through: :job_entries_jobs
end
求职
class JobEntry < ActiveRecord::Base
has_many :attachments
has_many :job_entries_jobs
has_many :pinned_entries, through: :job_entries_jobs
has_many :jobs, through: :job_entries_jobs
belongs_to :user, class_name: 'User', foreign_key: 'user_id'
end
JobEntriesJob
class JobEntriesJob < ActiveRecord::Base
self.table_name = 'job_entries_jobs'
has_many :pinned_entries
belongs_to :job_entry
belongs_to :job, touch: true
end
PinnedEntry
class PinnedEntry < ActiveRecord::Base
self.table_name = "pinned_entries"
belongs_to :job_entries_job
has_and_belongs_to_many :users
end
用户
class User < ActiveRecord::Base
has_many :job_entries
has_many :pinned_entries
end
我可以通过associations 以rails 方式使用job_id 和user_id(job_id 和user_id 从request 参数获取)获得pinned_entries(我可以使用SQL 获得pinned_entries)。如果是,我应该把这个code 放在哪里?
如果我有一个attachment 模型怎么样
class Attachment < ActiveRecord::Base
self.table_name = 'attachments'
belongs_to :job_entry, :class_name => 'JobEntry', :foreign_key => 'job_entry_id'
end
我想includeattachment(链接和文件名)和JobEntry(content)?
这是应该的输出
{
"listPinnedEntries": [
{
"id": 1
"user_id":
"text": "content of entry",
"user": {
"id":
"username": "jamesnguyen"
},
"attachments": [
{
"id":
"job_entry_id":
"comment": "file name",
"file": {
"url": "link here"
}
},
{
"id":
"job_entry_id":
"comment": "file name",
"file": {
"url": "link here"
}
}
]
}]
}
感谢您的帮助
【问题讨论】:
-
尝试在您的视图中执行
user_id.pinned_entries,这将查看与该特定user相关的所有条目。 -
感谢您的帮助。我已经稍微更新了这个问题。你能再读一遍吗?
标签: ruby-on-rails ruby-on-rails-4 activerecord associations rails-activerecord