gpt4 book ai didi

mysql - ROR协会|未定义方法 `map' 对于 nil :NilClass

转载 作者:行者123 更新时间:2023-11-29 17:07:32 24 4
gpt4 key购买 nike

当我想发布我的帖子时,我有这个: See the problem

我在 Archlinux 上使用 Rails。

这是我的 Controller 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。我想使用简单的关联形式,但我不知道它如何正常工作。

提前感谢您的包容,我是法国人,英语不好。

最佳答案

如果无法保存@post,则必须在“create”操作上定义@categories(以及“new”操作所需的任何其他变量)。

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 的编辑路径,而不是渲染 :new (您确定要渲染 :new 吗?)

关于mysql - ROR协会|未定义方法 `map' 对于 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com