0

I'm trying to create an instance variable inside the create method of one controller and then to use it in the view of another controller. Is this possible?

I'm creating the @content variable within the 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 = /\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

And I'm trying to use it in a partial that's used in the view of class StaticPages but it doesn't work:

<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>

3 Answers 3

0

I think your problem is not related to use an instance variable in the view of a different controller, but to use an instance variable in a partial:

You can use the @content instance variable in the view rendered by static_pages/home, whichever is the calling Controller. But you can't use the intance variable in a partial. You need to give it as a local variable of your partial, and use it as a local variable in the partial. There is several syntaxes to pass local variables in a partial, see example in Rails guide on layouts and rendering 3.4.4.

In the code you posted, feed_item is likely to be such a local variable of your partial.

Sign up to request clarification or add additional context in comments.

Comments

0

Either put it in the database, or use flash its if the 2 methods are one after the other..

Comments

0

You cannot use the instance variable set in one controller in another controller's view. You need to have it set in StaticPagesController or you could use a helper.

This might help : Rails: Set a common instance variable across several controller actions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.