gpt4 book ai didi

ruby-on-rails - 如何修改 to_json 方法并向其添加动态属性 - Rails 4

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:20 25 4
gpt4 key购买 nike

所以我有这个 Controller ,我想在@events 实例变量中添加一个动态属性以及其他数据

我搜索并尝试过类似@events.attributes.merge(appointment: true)

appointment = true 是我要添加到事件对象的内容。

def find
params = event_params

current_user = 2
@events = Event.where('date LIKE ?',"%#{params[:month]}%")

def @events.as_json(options = { })
h = super(options)
h[:appointments] = false # Or combine with above h[:appointments] = self.appointments?
h
end

respond_to do |format|
if current_user == 1

if @events

format.json {
render json: @events.to_json
}
else
render 'index'
end
else

format.json {
render json: @events.to_json
}
end
end

结束

此处为 ajax 代码

function retrieve(date_partial) {

var jsondata = {
events: {
month: date_partial,
}
}

$.ajax({
cache: false,
type: "POST",
url: "/events/find",
data: jsondata,
success: function(data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
var day = data[i].date.substring(0, 2);
$("td[data-day='" + day + "']").addClass('added');
}

},
error: function(xhr) {
alert("The error code is: " + xhr.statusText);
}
});

那么我该如何添加该属性呢?

最佳答案

这行得通吗?但也许 JSON 输出不是您所期望的?

format.json { render :json => {events: @events, appointments: true} }

关于ruby-on-rails - 如何修改 to_json 方法并向其添加动态属性 - Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32040530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com