我正在开发一个react本机应用程序,作为项目的一部分,我正在使用Ruby on Rails 5在API Only模式下使用ActiveAdmin为管理界面构建API。我有一切设置,而且一切运作良好。
在获得API的想法之前,我获得了一个文件中的数据,我需要使用rails复制其结构,因此它可以是内容可管理的。
但我似乎无法使主动记录关联正确。
这是数据文件的示例......
{
name: 'Scottish Stoics',
days: [
{
day: 'Monday',
meeting: [
{
name: 'Meeting one',
location: 'Test',
startTime: '11.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting two',
location: 'Test',
startTime: '10.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting three',
location: 'Test',
startTime: '10.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
],
},
{
day: 'Tuesday',
meeting: [
{
name: 'Meeting one',
location: 'Test',
startTime: '10',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting two',
location: 'Test',
startTime: '10',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting three',
location: 'Test',
startTime: '10',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
],
},
],
},
{
name: 'Scottish Cycling Group',
days: [
{
day: 'Sunday',
meeting: [
{
name: 'Meeting one',
location: 'Test',
startTime: '11.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting two',
location: 'Test',
startTime: '10.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting three',
location: 'Test',
startTime: '10.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
],
},
{
day: 'Tuesday',
meeting: [
{
name: 'Meeting one',
location: 'Test',
startTime: '10.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting two',
location: 'Test',
startTime: '10.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
{
name: 'Meeting three',
location: 'Test',
startTime: '10.00',
address: 'Test Street',
meetingLength: '1 Hour',
city: 'Edinburgh',
},
],
},
],
}
我有一个群组模型,日模型和会议模型。
组
belongs_to :day
belongs_to :meeting
会议
has_many :groups
日期
has_many :groups
我得到了这个结果。
[
{
id: 1,
name: "Scottish Stoics",
created_at: "2018-03-19T11:47:50.818Z",
updated_at: "2018-04-12T10:50:05.179Z",
day_id: 7,
meeting_id: 81
},
{
id: 2,
name: "Scottish Cycling Group",
created_at: "2018-03-19T11:47:57.498Z",
updated_at: "2018-04-11T22:13:26.656Z",
day_id: 7,
meeting_id: 83
},
]
现在我可以使用jbuilder来获取日期名称和会议名称,这很好,但我不能做的是选择一天的多次会议,以及为小组选择多天。这种数据结构在Rails中是否可行?
如果我应该使用不同类型的关联,我无法解决问题,任何人都可以为我阐明这一点吗?
答案 0 :(得分:1)
假设顶级嵌套对应组,您可以形成如下关联:
日期强>
has_many :meetings
belongs_to :group
<强>会议强>
belongs_to :day
<强>组强>
has_many :days
has_many :meetings, through: :days
虽然我的印象是在JSON中提供它应该是meetings
而不是meeting
来保持RESTful