【发布时间】:2019-01-31 07:31:36
【问题描述】:
当我想发布我的帖子时,我有这个: See the problem
我在 Archlinux 上使用 Rails。
这是我的控制器 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。 我想使用简单的关联形式,但我不知道它是如何正常工作的。
提前感谢您的宽容,我是法国人,我的英语不好。
【问题讨论】:
-
你能在这里添加整个错误转储吗.. 然后我们可以快速找出它繁荣从哪里出来?
-
我觉得它失败了,当编辑/创建失败时......所以
@categories也必须在创建和更新操作中定义
标签: mysql ruby-on-rails ruby associations