2012-09-01 31 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種方法是一前一後..

相關問題