【问题标题】:How do I show a specific view for the users resource?如何显示用户资源的特定视图?
【发布时间】:2012-03-01 02:46:07
【问题描述】:

我有两个模型:

User
has_many :prices

Price
belongs_to :users

我想显示这样的视图:

<% show this view if price belongs to current user %>
 <div> Price of Current User </div>
<% end %>

我该怎么做?

【问题讨论】:

  • 我不确定我是否理解你的问题,但&lt;%= current_user.prices %&gt; 不会覆盖你吗?
  • @shuriu 我改变了我的问题以使其更有意义。

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 devise


【解决方案1】:

首先,Price模型中的关联应该是

belongs_to :user #not users

其次,我仍然不确定我是否理解这个问题,但我会给你我的 2 美分:

如果您只想在视图中显示当前用户的价格:

<% current_user.prices.each do |price| %>
  <div><%= price %></div>
<% end %>

这将输出每个用户的价格。

如果您正在循环浏览所有价格,并且希望在价格属于用户时显示某些内容,您可以使用如下内容:

<% @prices.each do |price| %>
  <div><%= price %>
    <% if price.user == current_user %>
    <span> << out of all the prices, this is yours</span>
    <% end %>
  </div>
<% end %>

假设您在控制器中定义了@prices (@prices = Price.all) 和 current_user,这段代码循环遍历所有价格,并在价格属于当前用户时添加一个跨度。

希望这对您有所帮助。另外,请查看 this guide 了解关联以及您可以使用它们做什么。

【讨论】:

  • 我应该更清楚。该视图使用show action,所以我只会看到每页一个价格。无论哪种方式,它都解决了我的问题。谢谢。
【解决方案2】:

条件中的= 应该是==

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2021-03-06
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多