Ассоциация РОР |неопределенный метод `map 'для nil: NilClass - PullRequest
0 голосов
/ 24 августа 2018

Когда я хочу опубликовать свое сообщение, у меня есть это: Смотри проблему

Я использую Rails на Archlinux.

Это мой контроллер posts_controller.rb:

module Admin
  class PostsController < ApplicationController
    before_action :set_post, :set_categories, only: [:update, :edit, :destroy]
    layout 'back'
    def index
      @posts = Post.all.order('created_at DESC')##.page(params[:page]).per(10)
    end

    def new
      @posts = Post.new
      @users = current_user
      @categories = Category.all.map{|c| [ c.name, c.id ] }
    end

    def create
      @posts = Post.new(post_params)
      @posts.category_id = params[:category_id]
      if @posts.save
        redirect_to({action: :index}, success: "L'article à bien été crée")
      else
        render :new
      end
    end

    def edit
      @categories = Category.all.map{|c| [ c.name, c.id ] }
    end

    def update
      if @posts.update(post_params)
        @posts.category_id = params[:category_id]
        redirect_to({action: :index}, success: "L'article à bien été modifié")
      else
        render :new
      end
    end

    def destroy
      @posts.destroy
      redirect_to({action: :index}, success: "L'article à bien été supprimé")
    end

    private

    def post_params
      params.require(:post).permit(:title, :meta, :description, :precontent, :content, :category_id)
    end

    def set_post
      @posts = Post.friendly.find(params[:id])
    end

    def set_categories
      @categories = Category.all
    end



  end
end

Это мой взгляд:

<div class="row">
  <div class="col-md-9">
    <div class="card">
      <div class="card-header">Ajouter un article</div>
      <div class="card-body">
        <%= simple_form_for @posts, url: [:admin, @posts], html:{class: 'form-horizontal'} do |f| %>
          <%= f.input :title, label: "Titre" %>
          <%= f.input :meta, label: "Meta TAGS (Référencement)" %>
          <%= f.input :description, label: "Description" %>
          <%= f.input :precontent, label: "Pré Contenu" %>
          <%= f.input :content, label: "Contenu" %>
          <button type="submit" class="btn btn-primary">Ajouter l'article</button>
      </div>
    </div>
  </div>
  <div class="col-md-3">
    <div class="card">
      <div class="card-header">Image & Catégories</div>
      <div class="card-body">
        <%= select_tag(:category_id, options_for_select(@categories), class: 'form-control') %>
        <% end %>
      </div>
    </div>
  </div>
</div>

Это моя модель Сообщение:

class Post < ApplicationRecord
  extend FriendlyId
  friendly_id :title, use: [:slugged]
  belongs_to :category
  belongs_to :user
end

Это моя модель Категория:

class Category < ApplicationRecord
  has_many :posts
end

Корабль связи - ManyToOne. Я хочу использовать простую форму с ассоциацией, но я не знаю, как она работает правильно.

Заранее спасибо за вашу снисходительность, я француз, и я не очень хорошо говорю по-английски.

1 Ответ

0 голосов
/ 24 августа 2018

Вы должны определить @categories (и любую другую переменную, необходимую для действия "new") в действии "create", если @post не может быть сохранен.

if @post.save
  ....
else
   @categories = Category.select(:name,:id).map{|c| [c.name, c.id]} #note the select, it will be faster than just calling all
   render :new
end

То же самое можно сделать для действия "обновление", но я бы рекомендовал просто перенаправить на путь редактирования @post вместо рендеринга: новый (вы уверены, что хотите рендерить: новый?)

...