post方法如何在Ruby on Rails中工作

时间:2018-12-15 14:43:51

标签: ruby-on-rails ruby post

我来自Python和Java背景,仅具有CSS,HTML,Ruby的基础知识,并尝试使用Ruby on Rails学习Web开发。我正在尝试遵循Michael Hartl上的教程。我不明白清单7.23中的} 方法在做什么。

post

根据我在API中跟踪的内容,它接受了两个都是字符串的非可选参数,但是在清单7.23中,第二个参数中突然出现了哈希语法require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest test "invalid signup information" do get signup_path assert_no_difference 'User.count' do post users_path, params: { user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } end assert_template 'users/new' end end ,使我困惑。谁能启发我?

2 个答案:

答案 0 :(得分:4)

我认为您在找错地方了,该链接显示cat。您需要http.post

发件人:https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/integration.rb

IntegrationTest post

并且:

def post(path, **args)
  process(:post, path, **args)
end

编辑:双尖

Ruby 2.0添加了关键字参数双精度。 当您有未知数量的参数时,基本上会使用单个splat(*),并将其作为def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil) request_encoder = RequestEncoder.encoder(as) headers ||= {} # rest end 传递。

array

双splat(**)的作用类似于*,但对于关键字参数:

def with_args(*args)
  p args
end

with_args(1,2,"a")
# [1, 2, "a"]

在ruby中,您可以调用不带def with_args(**args) with_keyword(args) end def with_keyword(some_key: nil, other_key: nil) p "some_key: #{some_key}, other_key: #{other_key}" end with_args(some_key: "some_value", other_key: "other_value") # "some_key: some_value, other_key: other_value" with_args(some_key: "some_value") # "some_key: some_value, other_key: " 的方法,并传递不带()的哈希,所以

{}

就像写作

with_args({some_key: "some_value", other_key: "other_value"})

查看此答案:What does a double * (splat) operator dohttps://medium.freecodecamp.org/rubys-splat-and-double-splat-operators-ceb753329a78

所以...

写作时

with_args some_key: "some_value", other_key: "other_value")

正在处理

post users_path, params: { user: { name:  "",
                                   email: "user@invalid",
                                   password:              "foo",
                                   password_confirmation: "bar" } }

process(:post, users_path, params: { user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } process中的含义是哈希值

params

process的其他关键字args无关紧要,散列全为{ user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } } ,所有其他关键字均为nil

希望有道理...

答案 1 :(得分:3)

啊!大的问题。这行:

class UsersSignupTest < ActionDispatch::IntegrationTest

表示该类是从ActionDispatch::IntegrationTest继承的。

ActionDispatch::IntegrationTest是Rails类。您正在查看Net::HTTP类的文档,该类是Ruby类。

Here's the API docs for the ActionDispatch::IntegrationTest methods.

一开始,在Ruby和Rails之间混为一谈非常普遍。 Rails是框架,Ruby是语言。