Rails:如何链接到局部文件?

3

目前我正在尝试做以下事情:

我为我的用户创建了几个部分文件(例如_show_signature.html.erb)。 现在我想在单击链接时显示它们。 在我的用户控制器中,我创建了一个新的操作:

  def show_signature
     @is_on_show_signature = true
  end

  def show_information
     @is_on_show_information = true
  end

在我的用户展示页面(user show.html.erb)中,我编写了以下代码:
<% if @is_on_show_information %>
    <%= render :partial => 'show_information' %>
<% elsif @is_on_show_signature %>
    <%= render :partial => 'show_signature' %>
<% end %>

在我的“导航栏”中,我写了以下内容:
  <ul>
    <li class="profile-tab">
      <%= link_to 'Information', show_information_path %>
    </li>
    <li class="profile-tab">
      <%= link_to 'Signature', show_signature_path %>
    </li>
  </ul>

在我的routes.rb文件中,我写了以下内容:
  map.show_information '/user-information', :controller => 'user', :action => 'show_information'
  map.show_signature '/user-signature', :controller => 'user', :action => 'show_signature'

现在我的问题是:点击“信息”链接将重定向我到http://localhost:3000/user-information(因为我在routes.rb中告诉了它这个路径 - 我想),然后我会得到一个错误。
uninitialized constant UserController

但这不是我想要的... 我的用户展示路径类似于:

http://localhost:3000/users/2-loginname

(通过编码

  def to_param
     "#{id}-#{login.downcase.gsub(/[^[:alnum:]]/,'-')}".gsub(/-{2,}/,'-')
  end

在我的用户模型中,我想要链接到类似于http://localhost:3000/users/2-test/user-information的东西。有什么想法如何实现?为什么会出现这个错误?


你可以通过使用ActiveSupport内置的parameterize来改进to_param。然后,to_param变成了:"#{id}-#{login.downcase.parameterize}" - Ben Crouse
1个回答

6
Rails 的约定是,模型本身是单数形式(User),但表格(users)和控制器(UsersController)都使用复数形式。这可能会导致初学者产生很大的困惑,即使在使用 Rails 工作多年后,有时也会犯诸如'user = Users.first'这样的错误。当你开始思考表名而不是类名时,这当然是无效的。
此外,要切换页面上元素的显示,您可能需要使用link_to_remote方法,该方法使用 AJAX 进行更新,而不是进行页面刷新。如果您可以接受完全的页面刷新,则这些操作将需要重定向到某个地方,例如页面引用者,否则您将得到空白页或错误,因为页面模板不存在。
通常做法是:
<ul>
  <li class="profile-tab">
    <%= link_to_remote 'Information', show_information_path %>
  </li>
  <li class="profile-tab">
    <%= link_to_remote 'Signature', show_signature_path %>
  </li>
</ul>

接下来的每个操作都会按照您指定的方式进行,但是页面模板show_information.rjs将如下所示:

page.replace_html('extra_information', :partial => 'show_information')

请记住,您需要有一个占位符来接收部分内容,因此只需用具有特定ID的元素包装可选部分:

<div id="extra_information">
  <% if @is_on_show_information %>
    <%= render :partial => 'show_information' %>
  <% elsif @is_on_show_signature %>
    <%= render :partial => 'show_signature' %>
  <% end %>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接