2012-09-01 32 views
0

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

我创建了@content变量MicropostsController内:

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 = /\[email protected]\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> 

回答

0

我觉得在不同的控制器的视图中使用实例变量你的问题是没有关系的,但是在部分使用实例变量:

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

在您发布的代码中,feed_item很可能就是您的偏好的一个局部变量。

0

要么把它在数据库中,或使用闪光灯的,如果2种方法是一前一后..

相关问题