【问题标题】:Using an instance variable in another view在另一个视图中使用实例变量
【发布时间】:2012-08-27 03:05:35
【问题描述】:

我试图在一个控制器的 create 方法中创建一个实例变量,然后在另一个控制器的视图中使用它。这可能吗?

我正在MicropostsController 中创建@content 变量:

class MicropostsController < ApplicationController
  before_filter :signed_in_user, only: [:create, :destroy]
  before_filter :correct_user, only: :destroy

  def create
    @micropost = current_user.microposts.build(params[:micropost])
    @content = 'test' #params[:micropost][:content]
    #pattern = /\A@\w+/

    #if params[:micropost][:content] =~ pattern
     # @content = params[:micropost][:content]
    #end

    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_path
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

我正在尝试在 StaticPages 类视图中使用的部分中使用它,但它不起作用:

<li id="<%= feed_item.id %>">
  <%= link_to gravatar_for(feed_item.user), feed_item.user %>
  <span class="user">
      <%= link_to feed_item.user.name, feed_item.user %>
  </span>
  <span class="content"><%= feed_item.content %></span>
  <span class="timestamp">
    Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
    <% if @content %>
      <%= @content %>
    <% else %>
      <%= 'no content' %>
    <% end %>
  </span>
  <% if current_user?(feed_item.user) %>
    <%= link_to "delete", feed_item, method: :delete,
                data: { confirm: "You sure?" },
                title: feed_item.content %>
  <% end %>
</li>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    我认为您的问题与在不同控制器的视图中使用实例变量无关,而是在部分使用实例变量:

    您可以在static_pages/home 渲染的视图中使用@content 实例变量,以调用Controller 为准。但是您不能在部分中使用实例变量。您需要将其作为局部变量提供,并将其用作局部变量。有几种语法可以在部分中传递局部变量,请参阅Rails guide on layouts and rendering 3.4.4 中的示例。

    在您发布的代码中,feed_item 很可能是您的局部变量。

    【讨论】:

      【解决方案2】:

      要么把它放在数据库中,要么如果这两种方法一个接一个,就使用 flash it..

      【讨论】:

        【解决方案3】:

        您不能在另一个控制器的视图中使用在一个控制器中设置的实例变量。 您需要在 StaticPagesController 中设置它,或者您可以使用帮助器。

        这可能会有所帮助:Rails: Set a common instance variable across several controller actions

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-24
          • 1970-01-01
          • 2023-03-08
          • 2020-09-14
          • 2022-07-21
          • 2018-07-25
          • 1970-01-01
          • 2023-03-28
          相关资源
          最近更新 更多