访问View层中的外部模型属性

时间:2015-05-12 15:30:31

标签: ruby-on-rails

我有三个模型,Movie,MovieCheckout和User。我在类之间建立了正确的关联。

在我的索引中,我想要显示每部电影以及谁检查过它。

Dim kcFormula As String

kcFormula = "=IF(OR(Table3[[#This Row],[Status]]=" & """Rejected""" & "," & "Table3[[#This Row],[Status]] =" & """Completed""" & "," & "Table3[[#This Row],[Status]]=" & """Not Implemented""" & ")," & """ """ & ",INDEX('AMLLAST'!$1:$1048576,MATCH(Table3[[#This Row],[ID]],'AMLLAST'!$E:$E,0),11))"
lastROW = ActiveSheet.UsedRange.Rows.Count
With Sheets("AML")
myRNG = "K2:" & "K" & lastROW
            Sheets("AML").Range(myRNG).NumberFormat = "General"
            Sheets("AML").Range(myRNG).Formula = kcFormula
End With

我想知道是否有类似这样的代码

<% @movie.each do |movie| %>

   <% MovieCheckout.find_by movie_id: movie.id %> //I want to display MovieCheckout's user_id here.

<% end %>

我想把这个逻辑放在我的MovieController

<% MovieCheckout.find_by movie_id: movie.id %>.user_id

但是我不能在视图层索引之外引用电影。

2 个答案:

答案 0 :(得分:0)

您正在尝试在<% %>标记之外执行Ruby代码。这意味着不评估.user_id部分。

尝试这样的事情:

<% MovieCheckout.find_by(movie_id: movie.id).user_id %>

事实上,这些东西不属于View。

答案 1 :(得分:0)

class MovieCheckout < ActiveRecord::Base
  belongs_to :movie
  belongs_to :user
end

class Movie < ActiveRecord::Base
  has_many :checkouts, class_name: MovieCheckout, inverse_of: :movie
end

<% @movie.each do |movie| %>

   <% for co in movie.checkouts %>
     <%= co.user.name %>
   <% end %>

<% end %>