如何将@instance变量传递给我的视图

时间:2019-01-13 14:56:46

标签: ruby-on-rails

我正在设置一个新的Web应用程序,并且想要添加个性化商品,例如,如果用户选择了“ ebay商品”。我只想显示eBay的报价。我该如何在视图中调用实例变量以呈现相关报价?

过去,我尝试使用@services.service_type@service.service_type并嵌套变量,例如@services.user.service_type,但似乎没有任何作用。

我的仪表板/index.html.erb

<% if current_user.is_ebay && @services.service_type %>
...
<% end %>

我的dashboards_controller

class DashboardsController < ApplicationController
  before_action :authenticate_user!

  def index
     @services = current_user.services
  end
 end

编辑

我的用户模型

class User < ApplicationRecord
  has_many :services
end

我的服务模型

class Service < ApplicationRecord
  belongs_to :user
end

1 个答案:

答案 0 :(得分:2)

@services = current_user.services
# this will generate activerecord relation meaning couple of records
# you cannot access the column directly like @services.service_type

# to print the services you can do something like this 
<% if current_user.is_ebay %>
    <% @services.each do |service| %>
      <%= service.service_type %>
    <% end %>
<% end %>