@mirbook

Как вывести переменные из контроллера в layouts rails?

Пытаюсь сделать небольшую админку для сайта, добавил mvc, и пытаюсь вывести данные в layouts, но вот как это сделать?

app/controllers/admin/text_zones_controller.rb
class Admin::TextZonesController < Admin::BaseController
  before_action :set_text_zone, only: [:show, :edit, :update, :destroy]

  def index
    @text_zones = TextZone.all
  end

  def new
    @text_zone = TextZone.new
  end

  def edit
  end

  def create
    @text_zone = TextZone.new(text_zones_params)

    if @text_zone.save
      redirect_to admin_text_zones_path, :notice => "Текстовая зона успешно создана"
    else
      render action: :new
    end
  end

  def update
    if @text_zone.update_attributes(text_zones_params)
      redirect_to admin_text_zones_path, :notice => "Текстовая зона успешно обновлена"
    else
      render action: :edit
    end
  end

  def destroy
    @text_zone.destroy
    session[:current_user_id] = nil
    redirect_to admin_text_zones_path, :notice => 'Текстовая зона успешно удалена'
  end

private

  def set_text_zone
    @text_zone = TextZone.find(params[:id])
  end

  def text_zones_params
    params.require(:text_zone).permit(
      :telephone,
      :address,
      :time_work,
      :email,
      :content,
      :enabled,
    )
  end  
end


/views/admin/text_zones/index.html.erb
<h1>Текстовые зоны</h1>


<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">Телефон</th>
      <th scope="col">Адресс</th>
      <th scope="col">Время работы</th>
      <th scope="col">Почта</th>
      <th scope="col">Текст</th>
    </tr>
  </thead>
  <tbody>
    <% @text_zones.each do |text_zone| %>
    <tr>
      <td><%= text_zone.telephone %></td>
      <td><%= text_zone.address %></td>
      <td><%= text_zone.time_work %></td>
      <td><%= text_zone.email %></td>
      <td><%= text_zone.content %></td>
      <td>
      <%= link_to 'Редактировать', edit_admin_text_zone_path(text_zone) %>
      <%= link_to 'Удалить', admin_text_zone_path(text_zone), 
      method: :delete, 
      data: { confirm: 'Точно хотите удалить?' } %></td>
    </tr>
    <% end %>
  </tbody>
</table>

<%= link_to 'Добавить новую текстовую зону', new_admin_text_zone_path, class:'btn btn-primary' %>


/views/admin/text_zones/_form.html.erb
<%= simple_form_for [:admin, @text_zone] do |f| %>
  <%= f.input :telephone, label: 'Телефон' %>
  <%= f.input :address, label: 'Адрес' %>
  <%= f.input :time_work, label: 'Время работы' %>
  <%= f.input :email, label: 'Почта' %>
  <%= f.input :content, label: 'Текст на странице' %>
  <%= f.submit 'Сохранить' %>
  <%= link_to 'Отменить', admin_text_zones_path %>
<% end %>


Добавил данные
SFrvs6jTT5Synw3Ctm8FZA.png

app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Shop</title>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#fff">
    <meta name="format-detection" content="telephone=no">

    <link rel="apple-touch-icon" sizes="180x180" href="files/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="files/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="files/favicon-16x16.png">
    <link rel="manifest" href="files/site.webmanifest">
    <meta name="msapplication-TileColor" content="#da532c">
    <meta name="theme-color" content="#ffffff">
<!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]-->

    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>


 <body class="homepage">
<%= render 'shared/header' %>
<%= yield %>


Добавил переменную в контроллер:
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  layout 'application'

def index
@tel = TextZone.find(1)
end

end


app/views/shared/_header.html.erb
<header class="header">
      <div class="container">
        <div class="header__row row">
          <div class="header__logo"><a href="#"><%= image_tag 'logo.png' %></a></div>
          <div class="header__contact header__contact--1">
            <a class="tel" href="tel:88005553535"><i class="icon icon-phone"></i></a><%= @tel %>


база pg
rails 5.2
ruby 2.5.3

1) При этом выводится значение во вьюхе на главной - 5MNs8oU7QmaMaIav_i-vaQ.png#<TextZone:0x00007f319250f170>

2) А тут ничего пусто localhost:3000/text_zones/1
cYeQnuZ8RwmrW8beWWNSug.png

хотя хотелось бы вывести телефон и другие поля из админки, как это сделать?
  • Вопрос задан
  • 246 просмотров
Решения вопроса 1
alfss
@alfss
https://career.habr.com/alfss
Вы получили объект, надо обратится к его полям.
@tel.to_s
@tel.telephone
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы