Rails actions 和 jbuilder,为什么要这么难?
Rails actions and jbuilder, why they have to be as difficult?
Rails 快把我逼疯了。我正在尝试通过 JSON 的操作来响应。
我的目标是让 JSON 成为响应 URL.
的唯一格式
让我们看一些代码。
Model 是 Devise 用户,添加了一些字段。
控制器 是我的 UsersController
有这个动作
# /app/controllers/users_controller.rb
def static
render json: current_user
end
我也有这个 jbuilder 视图
# /app/views/users/static.json.jbuilder
json.content format_content(@user.content)
json.author do
json.name @user.name
json.email_address @user.email
end
if current_user.admin?
json.someValue "foo"
end
this View 没有做一些有趣的事情,但这只是一个尝试。
无论如何,我永远不会得到 static.json.jbuilder
内容。我总是将所有 Devise 用户的内容作为 JSON.
我做错了什么吗? (或者更好:我在哪里完成了史诗般的失败?)
总之找到了解决方案:
# /config/route.rb
get 'my-static-json' => 'mycontroller#static', defaults: {format: :json}
# /app/controllers/mycontrollers_controller.rb
def my-static-json
end
# /app/views/mycontrollers/my-static-json.json.jbuolder
json.content "some static content"
这只是一个示例,但提供了我需要的所有信息
Rails 快把我逼疯了。我正在尝试通过 JSON 的操作来响应。 我的目标是让 JSON 成为响应 URL.
的唯一格式让我们看一些代码。
Model 是 Devise 用户,添加了一些字段。
控制器 是我的 UsersController
有这个动作
# /app/controllers/users_controller.rb
def static
render json: current_user
end
我也有这个 jbuilder 视图
# /app/views/users/static.json.jbuilder
json.content format_content(@user.content)
json.author do
json.name @user.name
json.email_address @user.email
end
if current_user.admin?
json.someValue "foo"
end
this View 没有做一些有趣的事情,但这只是一个尝试。
无论如何,我永远不会得到 static.json.jbuilder
内容。我总是将所有 Devise 用户的内容作为 JSON.
我做错了什么吗? (或者更好:我在哪里完成了史诗般的失败?)
总之找到了解决方案:
# /config/route.rb
get 'my-static-json' => 'mycontroller#static', defaults: {format: :json}
# /app/controllers/mycontrollers_controller.rb
def my-static-json
end
# /app/views/mycontrollers/my-static-json.json.jbuolder
json.content "some static content"
这只是一个示例,但提供了我需要的所有信息