[英]How work render action in controller?
I have method in controller like this: 我在控制器中有这样的方法:
def create
@player = Player.new(player_params)
if @player.save
flash[:success] = "Player created"
redirect_to player_path(@player)
else
render 'new'
end
end
And I have also test: 而且我还测试了:
it "add players without nickname" do
visit new_player_path
click_button "Add player"
current_path should eq new_player_path
end
But after call render
method my current path is: 但是在调用render
方法之后,我当前的路径是:
not 不
But the layout is from players/new
. 但是布局是来自players/new
。 Why? 为什么? And what should be my test? 那我应该考什么? In test I just want to check if user don't type in nickname in nickname
filed application return to create user page (players/new path). 在测试中,我只想检查用户是否在nickname
提交应用程序中不输入昵称,以返回创建用户页面(玩家/新路径)。
Actually when there is any errors then it moves from new
to create
action, so the path becomes http://localhost:3000/players , and the render
just renders the new action's template here. 实际上,当出现任何错误时,它会从new
转到create
动作,因此路径变为http:// localhost:3000 / players ,并且render
仅在此处渲染新动作的模板。 Now the main question is why so? 现在的主要问题是为什么呢?
As in the new action you have submitted the form with some data to the create
action. 与在新操作中一样,您已将带有一些数据的表单提交到了create
操作。 Now if suppose it sends you back to new
action then it would have to redirect
you back to that page, so what will redirect
do? 现在,如果假设它使您返回到new
操作,那么它将不得不redirect
您redirect
回该页面,那么redirect
做什么? It will make rails to loose all the form data which you have submitted and the data would never persist. 这将使Rails失去所有您提交的表单数据,并且数据将永远不会持久。 So instead what is done is you remain on the create
action which has the url: http://localhost:3000/players and it renders the new
action which means the new
action's template (or you can say form). 因此,相反,要做的是保留在具有URL: http:// localhost:3000 / players的create
动作上,并呈现new
动作,这意味着new
动作的模板(或者可以说是表单)。 It doesn't redirects it just renders it in the same one. 它不会重定向,而只是将其呈现在同一文件中。
Now the question is how does the data persist? 现在的问题是数据如何持久保存? The data persists with the object. 数据与对象一起保留。 This line @player = Player.new(player_params)
creates a new object of the Player
class with the attributes you have passed in the form. 这行@player = Player.new(player_params)
使用您在表单中传递的属性创建Player
类的新对象。 Now as you remain in the same action and the object is persisted so the data on the form is also persisted. 现在,当您保持相同的操作并且对象被保留时,表单上的数据也将被保留。
If you want to test it then in your code replace this: 如果要测试它,则在代码中替换为:
render 'new'
with: 有:
redirect_to new_player_path
and you will notice the data would never persist unless you pass that explicitly. 并且您会注意到,除非您明确地传递了数据,否则数据将永远不会持久。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.