Rails attr_accessor 来自不同的控制器
Rails attr_accessor from different controller
以下是我的home_controller:
class HomeController < ApplicationController
def index
@products = Product.public_active.order('random()').limit(6).includes(:product_attachments).includes(:product_reviews)
end
end
和我的 product.rb 模型
class Product < ActiveRecord::Base
has_many :product_attachments, dependent: :destroy
accepts_nested_attributes_for :product_attachments, allow_destroy: true
attr_accessor :product_display
attr_accessor :product_overview_url
def set_extra_attributes
self.product_overview_url = self.product_attachments[0].attachment.medium.url
end
def set_cover_photo
self.product_display = self.product_attachments.find(self.cover_id).attachment.url
end
end
在我的主页视图 app/views/home/_product_section.html.erb
中,我无法访问 product_display
<div class="row">
<% @products.each do |product| %>
<div class="img-holder">
<a href="<%= product_path product %>">
<img src="<%= product.product_display %>" alt="<%= product.name %>" style="width: 100%;">
</a>
</div>
<% end %>
</div>
但我可以从我的 app/view/products/index.html.erb
页面模板访问 self.product_overview_url
。我需要建立关系以便 home_controller
可以访问 product.rb
模型吗?谢谢!!
在 set_extra_attributes 和 set_cover_photo 方法中,self 不是必需的,因为这些是引用实例属性的实例方法。
def set_extra_attributes
product_overview_url = product_attachments[0].attachment.medium.url
end
def set_cover_photo
product_display = product_attachments.find(cover_id).attachment.url
end
结束
您需要确保 product_display 设置为某些内容。
以下是我的home_controller:
class HomeController < ApplicationController
def index
@products = Product.public_active.order('random()').limit(6).includes(:product_attachments).includes(:product_reviews)
end
end
和我的 product.rb 模型
class Product < ActiveRecord::Base
has_many :product_attachments, dependent: :destroy
accepts_nested_attributes_for :product_attachments, allow_destroy: true
attr_accessor :product_display
attr_accessor :product_overview_url
def set_extra_attributes
self.product_overview_url = self.product_attachments[0].attachment.medium.url
end
def set_cover_photo
self.product_display = self.product_attachments.find(self.cover_id).attachment.url
end
end
在我的主页视图 app/views/home/_product_section.html.erb
中,我无法访问 product_display
<div class="row">
<% @products.each do |product| %>
<div class="img-holder">
<a href="<%= product_path product %>">
<img src="<%= product.product_display %>" alt="<%= product.name %>" style="width: 100%;">
</a>
</div>
<% end %>
</div>
但我可以从我的 app/view/products/index.html.erb
页面模板访问 self.product_overview_url
。我需要建立关系以便 home_controller
可以访问 product.rb
模型吗?谢谢!!
在 set_extra_attributes 和 set_cover_photo 方法中,self 不是必需的,因为这些是引用实例属性的实例方法。
def set_extra_attributes
product_overview_url = product_attachments[0].attachment.medium.url
end
def set_cover_photo
product_display = product_attachments.find(cover_id).attachment.url
end
结束
您需要确保 product_display 设置为某些内容。