Dmitry
Dmitry

Reputation: 157

Cross Controller variables in Ruby-on-Rails

I have a view with code:

   <section>
  <h1>
    <%= render @client %>
  </h1>
  <h2>
    <%= render @client.telnumbers %>
  </h2>
  <h3>
    <%= link_to 'New Tel', new_telnumber_path, :locals => { :client => @client }, :remote => true %>
  </h3>
</section>

But in my Telnumbers Controller - variable @client - nil What can I see my @client ?

My Telnumbers controller:

class TelnumbersController < ApplicationController
  def new
    @telnumber = Telnumber.new
    @telnumber.client_id = @client.id 
  end

  def create
    @telnumber = Telnumber.new(params[:telnumber])
    render :action => :new unless @telnumber.save
  end
end

So I have Error Called id for nil ...

I solved it by adding variables into new_telnumber_path

<%= link_to 'New Tel', new_telnumber_path(:client_id => @client.id ), :remote => true, :class => 'btn btn-small' %>

And in Controller:

  def new
    @telnumber = Telnumber.new
    @client = Client.find(params[:client_id]) 
    @telnumber.client_id = @client.id 
  end

Thanks!

Upvotes: 0

Views: 322

Answers (1)

Christoph Petschnig
Christoph Petschnig

Reputation: 4157

Every one of your controllers inherits by default from your ApplicationController. You can put a before_filter there that assigns the variables that you want to use in many (or every) controllers.

Here is an example:

class ApplicationController < ActionController::Base
  before_filter :set_client

  private

  def set_client
    # set the @client variable: load client from session or whatever your app logic is
  end
end

You can read here more about controller filters in Rails: http://guides.rubyonrails.org/action_controller_overview.html#filters

Upvotes: 3

Related Questions