Нет легкого метода. Что касается startup.sh и catalina.sh, работает кот, когда они заканчивают. Хотя, внутренне, кот все еще инициализирует и стартовые контексты.
Это помогло бы знать, пытались ли Вы узнать, закончил ли Ваш контекст загружаться или если Вы просто желаете генерала, "Tomcat работает, хотя Ваши контексты не могли бы быть полностью загружены..."
, Если это - последний, Вы могли бы создать веб-приложение, которое просто имеет слушателя контекста, который выполнит сценарий с помощью Времени выполнения. Если бы Вы были удобны, то Вы могли бы сделать веб-приложение configuable через файл web.xml для принятия параметра, который указывает на сценарий для выполнения.
Along the same lines as Rishav:
link_to "User Posts", [@user, :posts]
Here's an explanation from my blog.
Really early on in Rails, you would write routes like this:
redirect_to :controller => "posts", :action => "show", :id => @post.id
What this would do is dutifully redirect to the show
action inside the PostsController
and pass along the id
parameter with a
value of whatever @post.id
returns. Typical 302 response.
Then Rails 1.2 came along and allowed you to use routing helpers, like this:
redirect_to post_path(@post)
And the people rejoiced.
This would do effectively the same thing. post_path
here would build a route using the @post
object that would look something
например / posts / 1
, а затем redirect_to
отправит ответ 302 на этот маршрут, и браузер последует по нему.
Затем более поздние версии (я не могу вспомнить, какой именно ), допустимый синтаксис такой:
redirect_to @post
И люди обрадовались во второй раз.
Любая достаточно продвинутая технология неотличима от магии.
Хотя это кажется магией, это не так. То, что это делает, на самом деле очень и очень аккуратно. Метод redirect_to
, как и его двоюродные братья link_to
и form_for
, все используют общий метод для создания URL-адресов, называемый url_for
. Метод url_for
принимает много разных
varieties of objects, such as strings, hashes or even instances of models, like in the example above.
What it does with these objects then, is quite neat. In the case of the redirect_to @post
call above, it inspects the @post
object, sees that it is an object of the Post
class (we assume, anyway) and checks to see if that object has been persisted in a
где-то в базе данных, вызвав ?
.
Под «постоянным» я подразумеваю, что у объекта Ruby есть соответствующая запись где-то в базе данных. Метод persisted?
в Active Record реализован следующим образом:
def persisted?
!(new_record? || destroyed?)
end
Если объект не был создан с помощью вызова, такого как Model.new
, то он не будет новым запись, и если для нее не был вызван метод destroy
, она не будет
уничтожен тоже. Если оба этих случая верны, то это означает, что объект, скорее всего, был сохранен в базе данных в форме записи.
Если он был сохранен, то url_for
] знает, что этот объект можно найти
somewhere, and that the place it can be found is most likely under a method called post_path
. So it calls this method, and passes
in the to_param
value of this object which is usually the id
.
In short, it's effectively doing this:
#{@post.class.downcase}_path(@post.to_param)
Which comes out to being this:
post_path(1)
And when that method is called you would get this little string:
"/posts/1"
Lovely!
This is called polymorphic routing. You can pass an object to methods like redirect_to
, link_to
and form_for
and it will
попытаться определить правильный URL-адрес того, что использовать.
Теперь, когда вы кодируете Rails, вы, возможно, очень давно использовали form_for
вот так:
<% form_for @post, :url => { :controller => "posts", :action => "create" } do |f| %>
Конечно, с усовершенствованиями в Rails вы можете упростить его до следующего:
<% form_for @post, :url => posts_path do |f| %>
Потому что форма по умолчанию будет иметь HTTP-метод POST
и, следовательно, запрос к posts_path
собирается пойти в
действие create
для PostsController
, а не действие index
, что и произошло бы, если бы это был запрос GET
.
Но зачем останавливаться на достигнутом? Почему бы просто не написать это?
<%= form_for @post do |f| %>
Лично я не вижу причин не ... если это так просто. Метод form_for
использует url_for
внизу, как и
redirect_to
to work out where the form should go. It knows that the @post
object is of the Post
class (again, we assume) and it
checks to see if the object is persisted. If it is, then it will use post_path(@post)
. If it's not, then posts_path
.
The form_for
method itself checks to see if the object passed in is persisted also, and if it is then it'll default to a PUT
HTTP
method, otherwise a POST
.
So this is how form_for
can be flexible enough to have an identical syntax on both a new
and edit
view. It's becoming more and
more common these days for people to even put their whole form_for
tags into a single partial and include it in both the new
and
edit
pages.
So form_for
is fairly simple for when you pass a normal object, but what happens if you pass an array of objects? Like this, for
instance:
<%= form_for [@post, @comment] do |f| %>
Well, both url_for
and form_for
have you covered there too.
The url_for
method detects that this is an array and separates out each part and inspects them individually. First, what is this
@post
thing? Well, in this case let's assume it's a Post
instance that is persisted and has the id of 1. Second, what is this
@comment
объект? Это экземпляр комментария
, который еще не был сохранен в базе данных.
Здесь url_for
будет создавать вспомогательный метод URL по частям, помещая каждую часть в массив, объединив его в метод маршрутизации и затем вызвав этот метод маршрутизации с необходимыми аргументами.
Во-первых, он знает, что объект @post
относится к классу Post
и является сохраняется, поэтому вспомогательный URL-адрес будет начинаться с сообщения
. Во-вторых, он знает, что объект @comment
относится к классу Comment
и не сохраняется, и поэтому комментарии
последуют за ] post
во вспомогательной сборке URL.
to the end of that, resulting in post_comments_path
. Then it passes in just the persisted objects to the call to that method, resulting in a call like this:
post_comments_path(@post)
Calling that method results in this:
"/posts/1/comments"
Best part? form_for
will still know to use POST
if the @comment
object is not a persisted object, and PUT
if it is. A good
thing to remember is that the form_for
is always for the last object specified in the array. The objects prior to it are just its
nesting, nothing more.
The more objects that are added, the more times url_for
will do the hard yards and build the path out... although I recommend that
you keep it to just two parts.
Now that we've covered using an array containing objects for form_for
, let's take a look at another common use. An array containing
at least one Symbol object, like this:
<%= form_for [:admin, @post, @comment] do |f| %>
What the url_for
method does here is very simple. It sees that there's a Symbol
and takes it as it is. The first part of the
url
will simply be the same as the symbol: admin
. The URL that url_for
knows of at this point is just [:admin]
.
Then url_for
goes through the remaining parts of the array. In this case, let's assume both @post
and @comment
are persisted
и что они имеют идентификаторы 1 и 2 соответственно. Те же классы, что и раньше. url_for
затем добавляет сообщение
к создаваемому URL-адресу,
и комментарий
тоже, что приводит к [: admin,: post,: comment]
.
Затем происходит присоединение, в результате чего создается метод admin_post_comment_path
, и поскольку здесь сохраняются и @post
, и @comment
,
они передаются, что приводит к вызову этого метода:
admin_post_comment_path(@post, @comment)
Который (обычно) превращается в этот путь:
/admin/posts/1/comments/2
Вы можете использовать форму массива полиморфной маршрутизации с redirect_to
, link_to Методы
и form_for
. Наверное, есть другие
methods that I'm not remembering right now that can do it too... it's generally anything in Rails that would normally take a URL.
There's no need to build your URLs in any Rails version greater-than 2 using hashes; that's pretty old school.
Instead, experiment with your new knowledge of polymorphic routing and use it to the best of your advantage.
Это должно работать:
link_to "User Posts", user_posts_path(@user)
для получения более подробной информации посетите: