我有一个问题:我想在帖 subview 中显示图片。我有以下 Controller :
# 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”方法?有办法吗?
最佳答案
没有。
如果你想在你的帖 subview 中呈现你的图像,你应该让这些资源在你的 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 %>
关于ruby-on-rails - 在 RoR 中显示来自另一个 Controller 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23495173/