使用 Ruby on Rails 以不寻常的方式加载视图文件

发布于 2024-10-23 23:36:42 字数 953 浏览 1 评论 0 原文

我正在使用 Ruby on Rails 3,我想知道是否可以使用命名空间 URL 来过滤数据。

例如,我有一个这样声明的命名空间:

namespace "users" do
  resources :accounts
end

使用上面的代码,我可以访问 URL 上 id 1 的帐户数据(这会加载 RAILS_ROOT/app/views/users/accounts/ show.html.erb 文件)

http://localhost/users/accounts/2

我想要做的是浏览以下 URL

http://realer.com/users/2

,以加载位于 supervision.html.erb 的视图>users:

`RAILS_ROOT/app/views/users/supervision.html.erb` # This is the file that I would like to load

`RAILS_ROOT/app/views/users/accounts/new.html.erb`
`RAILS_ROOT/app/views/users/accounts/show.html.erb`
...

我想这样做,因为我希望每个操作都有单独的视图,然后将它们作为部分视图合并到一个文件中,在我的例子中 supervision.html.erb< /代码>。这样做时,我不必单独更改 show.html.erb 文件,这样我就可以保持此视图文件“不受影响”\“纯”,并且可以将其加载到其他观点。也就是说,show.html.erb 必须仅用于执行一件事,因此不得加载其他部分。

I am using Ruby on Rails 3 and I would like to know if it is possible to use a namespaced URL to filter data.

For example, I have a namespace stated like this:

namespace "users" do
  resources :accounts
end

Using the above code I can access account data with id 1 at the URL (this load the RAILS_ROOT/app/views/users/accounts/show.html.erb file)

http://localhost/users/accounts/2

What I would like to do is to browse the following URL

http://realer.com/users/2

in order to load a view named supervision.html.erb located in the main folder of users:

`RAILS_ROOT/app/views/users/supervision.html.erb` # This is the file that I would like to load

`RAILS_ROOT/app/views/users/accounts/new.html.erb`
`RAILS_ROOT/app/views/users/accounts/show.html.erb`
...

I thinked to approach like that because I would like to have separated views for each action and then incorporate all of them as partial views in a single file, in my case supervision.html.erb. Doing that I don't have to change, for example, the show.html.erb file individually so that I can keep this view file "untouched"\"pure" with the possibility of load that in other views. That is, the show.html.erb must be used to do one only thing, so in that must be not loaded other partials.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心欲静而疯不止 2024-10-30 23:36:42

如果您想要以不同的方式呈现视图文件本身,并且 URL 结构对您来说并不那么重要,您可以在控制器中执行此操作:

def show
  render 'users/supervision'
end

如果您确实想要更改URL 结构也是如此...我不确定是否有快捷方式可以做到这一点,但您始终可以这样做:

match 'users/:id' => 'accounts#show'

或者

match 'users/:id' => 'users/accounts#show'

If it's the view file itself that you're wanting to render differently, and the URL structure doesn't really matter as much to you you can do this in the controller:

def show
  render 'users/supervision'
end

If you really want to change the URL structure too ... I'm not sure if there's a shortcut way of doing it but you can always do this:

match 'users/:id' => 'accounts#show'

Or

match 'users/:id' => 'users/accounts#show'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文