我有两种模式:
User
has_many :prices
Price
belongs_to :users
我想要显示这样的观点:
<% show this view if price belongs to current user %>
<div> Price of Current User </div>
<% end %>
我该怎么做?
答案 0 :(得分:2)
首先,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以及你可以用它们做些什么。
答案 1 :(得分:0)
条件中的=
应为==
。