在我当前的rails程序中,当我使用类似的东西
user = User.find(10)
Run Code Online (Sandbox Code Playgroud)
当没有ID = 10的用户时,我会有例外:
ActiveRecord::RecordNotFound: Couldn't find User with ID=10
Run Code Online (Sandbox Code Playgroud)
我可以获得nil而不是提出异常,所以当我做以下事情时:
unless user = Challenge.find(10)
puts "some error msg"
end
Run Code Online (Sandbox Code Playgroud)
我只想在没有记录的情况下获得nil并且我不想使用begin/rescue
谢谢
我正在使用Rails 3.2.2,使用aasm gem,我有这样的Document模型:
class Document < ActiveRecord::Base
include AASM
aasm do
state :unread, :initial => true
state :read
state :closed
event :view do
transitions :to => :read, :from => [:unread]
end
event :close do
transitions :to => :closed, :from => [:read, :unread]
end
end
Run Code Online (Sandbox Code Playgroud)
现在在我的控制台上:
? ? bundle exec rails c
Loading development environment (Rails 3.2.2)
irb(main):006:0> Document.create!(:title => 'test')
(0.2ms) BEGIN
SQL (0.3ms) INSERT INTO `documents` (`aasm_state`, `checklist_id`, `created_at`, `description`, `dir`, `planned_date`, `procedure_id`, `section`, `subsection`, `title`, `updated_at`) …Run Code Online (Sandbox Code Playgroud) 如何用JSON对象回复一个简单的ruby rack服务器,让我们假设mt服务器是这样的:
app = Proc.new do |env|
[200, { 'Content-Type' => 'text/plain' }, ['Some body']]
end
Rack::Handler::Thin.run(app, :Port => 4001, :threaded => true)
Run Code Online (Sandbox Code Playgroud)
并假设我想要一个JSON对象而不是一些正文文本,例如:
{
"root": [
{
"function": null
}
]
Run Code Online (Sandbox Code Playgroud)
}
谢谢
我有一个非常简单的Ruby Rack服务器,如:
app = Proc.new do |env|
req = Rack::Request.new(env).params
p req.inspect
[200, { 'Content-Type' => 'text/plain' }, ['Some body']]
end
Rack::Handler::Thin.run(app, :Port => 4001, :threaded => true)
Run Code Online (Sandbox Code Playgroud)
每当我使用JSON对象向服务器发送POST HTTP请求时:
{ "session": {
"accountId": String,
"callId": String,
"from": Object,
"headers": Object,
"id": String,
"initialText": String,
"parameters": Object,
"timestamp": String,
"to": Object,
"userType": String } }
Run Code Online (Sandbox Code Playgroud)
我一无所获.我可以检测到收到的请求但无法获取数据.在我的控制台上的结果puts req.inspect是这样的:
"{}"
Run Code Online (Sandbox Code Playgroud)
我该如何获取数据?
我试图通过以下方式改变它:
request = Rack::Request.new env
object = JSON.parse request.body
puts JSON.pretty_generate(object)
Run Code Online (Sandbox Code Playgroud)
但我收到以下警告:
!! Unexpected error while processing request: can't …Run Code Online (Sandbox Code Playgroud) 我正在使用带有bundler的rails 3,我使用bundler安装了一个gem,现在我需要通过修改gem的控制器来稍微修改gem的流量,我该怎么做,我敢肯定有一个命令在本地安装文件,所以我可以修改它,我试图通过创建另一个具有相同名称但听起来不起作用的控制器来覆盖控制器.