Reputation: 141
I have a problem: I want to show images inside the post views. I have the following controllers:
# 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
and
# 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
How can I call the methods 'index' and/or 'show' of ImgsController inside the views/posts/index.html.erb? Is there a way?
Upvotes: 1
Views: 897
Reputation: 141
All the answers helped me to see the solution. I read the guide as Benjamin Sinclair said.
All I needed to do was put
@imgs = Img.all
inside the method 'index' of PostsController.
So, I called @imgs in views/posts/index.html.erb
Simple!
Thanks!
Upvotes: 0
Reputation: 6274
Nope.
If you want to render your images within your post views, you should make those resources available within your posts_controller.
I assume you have an association somewhat like
class Post
has_many :images
end
So you could do something like:
# posts/index.html.erb
<% @posts.each do |post| %>
<p><%= post.name %></p>
<% @post.images.each do |img|
<p><%= img.name %></p>
<% end %>
<% end %>
Upvotes: 4
Reputation: 10825
Of course, you can render any template file:
render "posts/show" # or index
I assume that you have logic that works with both or you controller variables.
Upvotes: 1