Rails 4:部分w / locals在一个地方工作但不是另一个......为什么?

时间:2015-07-19 23:56:49

标签: ruby-on-rails-4

如何解决?

正确渲染工作......

<% # jobs/_job.html.erb %>
<% # jobs/index.html.erb %>
<% # @jobs set in jobs#index %>

<%= render partial: 'jobs/job', locals: { jobs: @jobs } %>

什么都没有......

<% # users/show.html.erb %>
<% # @jobs set in users#show %>
<% # binding.pry shows @jobs is set %>
<% # binding.pry shows local jobs is set %>

<%= # render partial: 'jobs/job', locals: { jobs: @jobs } %>
<% # adding the following line per @ suggestion, but still not rendering %>
<%= render partial: 'jobs/job', object: @jobs %>

修改

<% # _job.html.erb %>
<% @jobs.each do |job| %>
<% # stuff %>
<% end %>

非常简单,但以防万一...

# users_controller.rb
def show
  @pups           = current_user.pups
  @availabilities = current_user.availabilities
  @jobs           = current_user.jobs
end  

1 个答案:

答案 0 :(得分:0)

_job应该只呈现单个作业实例的HTML视图

使用render partial:

渲染部分时要小心

对于views/object_name/_partial_name.html.erb中的部分定义,变量名partial_name是特殊的,因为它被视为视图所关注的主要对象。

换句话说

<强>作业/ _job.html.erb

<% do_something_with(job) 
# NOT @job nor @jobs nor jobs
# The partial name is _job.html.erb => use the variable `job`
%>

调用此partial时,您应使用object参数(对于单个实例)或collection来呈现这些对象的数组

用户/ show.html.erb

<%= render partial: 'jobs/job', collection: @jobs
# This is going to render the partial as many times as there are job in @jobs
%>

参见解释+示例in the doc

  

每个partial也有一个局部变量,其名称与partial(减去下划线)相同。您可以通过:object选项将对象传递给此局部变量:

简而言之,以下选项可行(在文档上滚动更多以获得第3和第4个的解释)

用户/ show.html.erb

<%= @jobs.each do |job|
  render 'jobs/job', locals: { job: job } 
%>
OR
<%= @jobs.each do |job|
  render partial: `jobs/job`, object: job 
%>
OR
<%= render partial: `jobs/job`, collection: @jobs %>
OR
<%= render @jobs %>