我遇到了一个问题:我想在帖子视图中显示图片。我有以下控制器:
# posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:show]
# GET /posts
# GET /posts.json
def index
if params[:search]
@posts = Post.search(params[:search]).order("created_at DESC")
else
@posts = Post.all.order('created_at DESC')
end
end
# GET /posts/1
# GET /posts/1.json
def show
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find_by_slug(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:titulo, :slug, :texto, :imagem)
end
end
和
# imgs_controller.rb
class ImgsController < ApplicationController
before_action :set_img, only: [:show]
# GET /imgs
# GET /imgs.json
def index
@imgs = Img.all
end
# GET /imgs/1
# GET /imgs/1.json
def show
end
private
# Use callbacks to share common setup or constraints between actions.
def set_img
@img = Img.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def img_params
params.require(:img).permit(:imagem, :nome, :descricao, :to_slide)
end
end
如何在 views / posts / index.html.erb 中调用 ImgsController 的方法'index'和/或'show'?有办法吗?
答案 0 :(得分:4)
不。
如果您想在帖子视图中呈现图片,则应该在posts_controller中提供这些资源。
我认为你的关联有点像
class Post
has_many :images
end
所以你可以这样做:
# posts/index.html.erb
<% @posts.each do |post| %>
<p><%= post.name %></p>
<% @post.images.each do |img|
<p><%= img.name %></p>
<% end %>
<% end %>
答案 1 :(得分:1)
答案 2 :(得分:0)
所有答案都帮助我看到了解决方案。 我读了这本指南,就像本杰明辛克莱所说的那样。
我需要做的就是把
@imgs = Img.all
在 PostsController 的方法'index'中。
所以,我在views / posts / index.html.erb中调用 @imgs
简单!
谢谢!