更新时间:2023-12-02 19:54:10
问题不在于实例变量中的数据,而在于序列化.
The problem is not with the data in in the instance variable but with the serialisation.
react_component
视图助手将在第二个参数(如果它不是字符串)上调用to_json
方法.在您的情况下:{calendar_items: @calendar_items}.to_json
,它可以递归工作,因此您要确保@calendar_items.to_json
返回期望的JSON输出.您可以在rails console
中使用@calendar_items.serializable_hash
对其进行测试,它会返回一个哈希值,该哈希值对于人类来说更易读.
The react_component
view helper will call the to_json
method on the second argument if it is not a string. In your case: {calendar_items: @calendar_items}.to_json
, which works recursively, so you want to make sure @calendar_items.to_json
returns the expected JSON output. You can use @calendar_items.serializable_hash
for testing it in the rails console
, it returns a hash, which is more readable for humans.
或者您将数据序列化为字符串,然后将其提供给react_component
.
Or you serialise your data into a string and feed the react_component
with it.
我不知道Rails 5序列化,但它似乎与 ActiveModelSerializers 类似,因此您可以在序列化输出中包括这些关系,例如:@calendar_items.to_jso(include: [:documents])
.在ActiveModelSerializers中,您可以为每个类指定一个序列化器,并指定它们之间的关系,这些关系可以自动包括在内.
I dont know Rails 5 serialization but it seems to be similar to ActiveModelSerializers so you can include the relationships in the serialised output like: @calendar_items.to_jso(include: [:documents])
. In ActiveModelSerializers you can specify a serialiser to each class, and specify the relationships on them, those can be included automatically.
一个可行的解决方案可能是:
So one working solution could be:
def show
calendar_items = CalendarItem.where(schedule: @schedule).includes(:people, :documents)
@react_component_props = { calendar_items: calendar_items.to_json(include: [:people, :documents]) }
end
= react_component('CalendarItemsList', @react_component_props)
一个小技巧:您可以在CalendarItem模型上创建一个by_schedule
范围,因此以后可以使用它:CalendarItem.by_schedule @schedule
A modest tip: you can create a by_schedule
scope on the CalendarItem model, so later you can use it: CalendarItem.by_schedule @schedule
编辑
如果需要在视图中其他位置放置数据,则可以使用as_json
方法:
If you need the data other places in the view then you can use the as_json
method:
def show
calendar_items_scope = CalendarItem.where(schedule: @schedule).includes(:people, :documents)
@calendar_items = calendar_items_scope.as_json(include: [:people, :documents])
end