Rails 5渲染部分和传递数据
我无法了解数据传递的一般方式,并且可供部分使用。
例如:
我有一个控制器将实例变量交给一个渲染部分的模板:
static_pages_controller.rb:
def home @feed_items = current_user.feed end
home.html.erb:
_feed.html.erb:
现在,在我的User模型中是一个实例方法,它进入数据库以获取她的post:
user.rb:
def feed Micropost.where("user_id = ?", id) end
因此,不知何故,因为Micropost.where(...)
返回一个微_feed.html.erb
的集合是Rails如何知道从_feed.html.erb
转到另一个部分,其中
_feed.html.erb
?
_micropost.html.erb:
<li id="micropost-">
而且它只是一个惯例,因为我真的处理一系列microposts
,Rails知道micropost
可变吗?
您可以在关于布局和渲染的Ruby on Rails指南中回答您的问题。 值得阅读下面引用的段落之前的部分信息:
每个partial也有一个局部变量,其名称与partial(减去下划线)相同。 您可以通过:object选项将对象传递给此局部变量:
<%= render partial: "customer", object: @new_customer %>
在customer partial中,customer变量将从父视图引用@new_customer。 (早期的指南指示为render()指定其他选项,例如object:,你必须明确指定
partial:
和partial:
的名称。)如果要将模型实例渲染为局部,则可以使用简写语法:
<%= render @customer %>
假设@customer实例变量包含Customer模型的实例,这将使用_customer.html.erb来呈现它,并将局部变量customer传递给partial,这将引用父视图中的@customer实例变量。
3.4.5渲染集合
部分在渲染集合时非常有用。 通过:collection选项将集合传递给partial时,将为集合中的每个成员插入一次partial:
index.html.erb:
Products
<%= render partial: "product", collection: @products %>_product.html.erb:
Product Name: <%= product.name %>
当使用复数集合调用partial时,partial的各个实例可以访问通过以partial命名的变量呈现的集合的成员。 在这种情况下,partial是_product,在_product partial中,您可以引用product来获取正在呈现的实例。
还有一个简写。 假设@products是产品实例的集合,您只需在index.html.erb中编写它就可以产生相同的结果:
Products
<%= render @products %>Rails通过查看集合中的模型名称来确定要使用的部分名称。 实际上,您甚至可以创建异构集合并以这种方式呈现它,并且Rails将为集合的每个成员选择适当的部分:
index.html.erb:
Contacts
<%= render [customer1, employee1, customer2, employee2] %>客户/ _customer.html.erb:
Customer: <%= customer.name %>
员工/ _employee.html.erb:
Employee: <%= employee.name %>
在这种情况下,Rails将根据集合的每个成员使用客户或员工部分。
如果集合为空,则render将返回nil,因此提供替代内容应该相当简单。
Products
<%= render(@products) || "There are no products available." %>