我知道有很多类似的帖子,人们有同样的问题,但没有一个帮助我。如果我创建新文章,那么它将没有类别。但是,如果我编辑之前在seed.rb中创建的文章,则更新类别。 怎么了?
分类表:
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.timestamps
end
end
end
category.rb
class Category < ActiveRecord::Base
has_many :articles
end
article.rb
class Article < ActiveRecord::Base
belongs_to :category
end
然后我有一个_form文件
<%= form_for(@article) do |f| %>
<div class="title">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="content">
<%= f.label :content %>
<%= f.text_field :content %>
</div>
<div class="category">
<%= f.label :category %>
<%= collection_select(:article, :category_id, Category.all, :id, :name) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
有一个categories_controller文件:
class CategoriesController < ApplicationController
def index
@categories = Category.all
end
def show
@category = Category.find(params[:id])
@articles = @category.articles
end
def new
@category = Category.new
end
def create
@category = Category.new(category_params)
if @category.save
redirect_to(:action => 'index')
else
render('new')
end
end
def edit
@category = Category.find(params[:id])
end
def update
@category = Category.find(params[:id])
if @category.update_attributes(category_params)
redirect_to(:action => 'show', :id => @category.id)
else
render('index')
end
end
def delete
@category = Category.find(params[:id])
end
def destroy
Category.find(params[:id]).destroy
redirect_to(:action => 'index')
end
private
def category_params
params.require(:category).permit(:name)
end
end
文章控制器文件:
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to(:action => 'index')
else
render('new')
end
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
if @article.update_attributes(article_params)
redirect_to(:action => 'show', :id => @article.id)
else
render('index')
end
end
def delete
@article = Article.find(params[:id])
end
def destroy
Article.find(params[:id]).destroy
redirect_to(:action => 'index')
end
private
def article_params
params.require(:article).permit(:title, :content)
end
end
答案 0 :(得分:0)
您似乎未在articles#create
操作中构建关联。 category_id是通过您的表单发送的,但您仍需要构建Active Record关联。您可以在文章控制器中尝试这样的事情:
def create
@article = Article.new(article_params)
@category = Category.find(params[:category_id])
@article.category = @category
if @article.save
redirect_to(:action => 'index')
else
render('new')
end
end
请注意,有多种方法可以创建关联。您的文章类具有以下five methods来操纵关联:
@article.category
@article.category=
@article.build_category
@article.create_category
@article.create_category!