Rails 4 - 从公共部分渲染STI模型

时间:2015-12-10 10:12:20

标签: ruby-on-rails ruby sti

我有这样的STI模型:Photo < MediumVideo < Medium。 在某个视图中,我想像那样向他们展示:

# app/views/albums/show.html.slim
ul
  li= render @album.media

render搜索albums/_photoalbums/_video部分:

# app/views/albums/_photo.html.slim
h3= photo.title
= image_tag photo.file.url
p= photo.description

# app/views/albums/_video.html.slim
h3= video.title
= video_tag video.file.url
p= video.description

现在,我想在app/views/albums/show.html.slim中创建一个模板,用于媒体之间不重复的公共字段。这样的事情:

# app/views/albums/_medium.html.slim
h3= medium.title
= yield(:medium_tag)
p= medium.description
= yield(:medium_additionnals)

# app/views/albums/_photo.html.slim
- content_for(:medium_tag) do
  = image_tag photo.file.url
- content_for(:medium_additionnals) do
  # any additionnals fields

# app/views/albums/_video.html.slim
- content_for(:medium_tag) do
  = video_tag video.file.url
- content_for(:medium_additionnals) do
  # any additionnals fields

但是这给了我收益率连接内容......

有人有解决方案/替代方案吗?

[编辑]

使用此模板:

# app/views/albums/show.html.slim
= render @album.media

# app/views/albums/_medium.html.slim
div
  h3= medium.title
  = yield(:medium_tag)

# app/views/albums/_photo.html.slim
- content_for(:medium_tag) do
  | TEST

生成的HTML:

<div>
  <h3>Photo1</h3>
  TEST
</div>
<div>
  <h3>Photo2</h3>
  TESTTEST
</div>
<div>
  <h3>Photo3</h3>
  TESTTESTTEST
</div>
<div>
  <h3>Photo4</h3>
  TESTTESTTESTTEST
</div>
...

产量结果与媒体计数一样多。

1 个答案:

答案 0 :(得分:1)

您的代码似乎非常好,但我不知道您的render来电是如何在每个medium项目中循环的

可以使用enter image description here来返回相关数据,虽然这不是最有效的:

#app/helpers/application_helper.rb
module ApplicationHelper
      output =  Slim::Engine.new  "h3={item.title}"
      output += Slim::Engine.new  "- eval(#{item.model_name.human}_tag) item.file.url"
      output += Slim::Engline.new "p=item.description"
   end
end

这将允许您运行:

#app/views/albums/_photo.html.slim
= media photo

#app/views/albums/_video.html.slim
= media video

-

或者,您可以将其放入_medium部分:

#app/views/albums/_photo.html.slim
= render partial: "medium", locals: { item: photo }

#app/views/albums/_video.html.slim
= render partial: "medium", locals: { item: video }
然后

_medium会有以下内容:

#app/views/albums/_medium.html.slim
h3=item.title
- eval("#{item.model_name.human}_tag") item.file.url
p=item.description