ruby-on-rails - 在 RoR 中显示来自另一个 Controller 的内容

标签 ruby-on-rails ruby ruby-on-rails-4

我有一个问题:我想在帖 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/

相关文章:

ruby - 有没有一种可接受的方法可以将多个模块声明放在同一行?

ruby-on-rails-4 - 受密码保护的特定 Rails 路线

ruby-on-rails - 获取错误 Apple 推送通知 OpenSSL::SSL::SSLError

ruby-on-rails - 在不是按字母顺序排列的情况下按尺寸名称订购商品?

ruby-on-rails - 如何在 Ruby 中访问深层嵌套哈希中的值?

arrays - 如何向数组添加多个元素?

ruby - RSpec 规范没有运行?

ruby-on-rails - 如何处理 Rails 4 中的枚举值

ruby-on-rails - rails 3 : Why might my respond_to statement throw this exception when called from a POST request?

mysql - MariaDB 10.0,innodb : Conditional Unique Constraint?