这是我所拥有的表格的片段。分配:title和:description在创建模型&#34; Post&#34;时工作得很好,但是当我尝试将category_id指定为1并且它没有分配任何内容时,category_id仍为nil。< / p>
.form-group
= f.input :title, input_html: { class: 'form-control' }
.form-group
= f.input :description, input_html: { class: 'form-control' }
.form-group
= f.input :category_id, input_html: { class: 'form-control' }
使用Post.find_by时(标题:&#39; posty&#39;(我给帖子的标题)) 我明白了......
=> #<Post id: 13, title: "posty", description: "eyyyyyy", created_at: "2016-03-07 17:45:05", updated_at: "2016-03-07 17:45:05", category_id: nil>
注意category_id:nil怎么样?它应该等于表格中指定的数字,但它不起作用。
这是Schema.rb的一个片段。它包含2个模型,类别和帖子,帖子属于某个类别。
create_table "categories", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "category_id"
end
add_index "posts", ["category_id"], name: "index_posts_on_category_id"
这是我的posts_controller代码
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all.order("created_at DESC")
end
def show
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post, notice: "Successfully created"
else
render 'new'
end
end
def edit
end
def update
if @post.update(post_params)
redirect_to @post, notice: "Post was successfully updated"
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
private
def post_params
params.require(:post).permit(:title, :description)
end
def find_post
@post = Post.find(params[:id])
end
end
答案 0 :(得分:0)
在posts_controller.rb
中,更改:
def post_params
params.require(:post).permit(:title, :description)
end
为:
def post_params
params.require(:post).permit(:title, :description, :category_id)
end