如何在没有类别控制器的情况下向rails中的帖子添加类别

Leo*_*n92 2 ruby ruby-on-rails database-relations

谢谢大家的高级帮助.

我是rails的绝对初学者,我正在努力完成一个教程.

任务如下.我有一个从脚手架构建的帖子模型,只有内容:字符串字段.

然后是一个类别模型,而不是一个脚手架等.这个想法是一个类别has_many:posts和post belongs_to:category.类别具有字段名称和描述.这很好,我理解这一点,我已经将这些添加到模型中.

我也进行了迁移

   rails generate migration AddCategoryToPost category:references
Run Code Online (Sandbox Code Playgroud)

我现在如何让用户在发布帖子时添加类别.

因此,事件的顺序是用户创建帖子,他们可以在创建帖子时添加类别.该类别具有用户需要定义的名称和描述.

  def new
   @post = Post.new
  end
  def create
   @category = Category.new(caregory_params)
   @post = Post.new(post_params)
   respond_to do |format|
    if @post.save
      format.html { redirect_to @post, notice: 'Post was successfully  created.' }
      format.json { render :show, status: :created, location: @post }
    else
      format.html { render :new }
     format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
 end
Run Code Online (Sandbox Code Playgroud)

如何更改post控制器的新方法,创建方法和更新方法以实现此目的,从而表单应包含什么来创建新帖子(和类别).

非常感谢你在高级方面的帮助,我只是不明白你将如何去做,因为类别需要是一个'对象',需要添加到post对象(需要添加到数据库) .

dim*_*ura 6

PostsController#create方法现在看起来像这样:

def create
  @post = Post.new(post_params)

  respond_to do |format|
    if @post.save
      format.html { redirect_to @post, notice: 'Post was successfully created.' }
      format.json { render :show, status: :created, location: @post }
    else
      format.html { render :new }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

post_params是这样的:

def post_params
  params.require(:post).permit(:title, :body)
end
Run Code Online (Sandbox Code Playgroud)

我还以为你已经定义之间的关系Category,并Post与相应迁移的数据库:

class Post < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :posts
end
Run Code Online (Sandbox Code Playgroud)

您需要的是添加Post在创建和更新时选择类别的功能.您只需要在两个地方进行更改.

第一个是表单view/posts/_form.html.erb,在form_for块中添加以下代码段:

<div class="field">
  <%= f.label :category_id %>
  <%= f.collection_select :category_id, Category.all, :id, :name %>
</div>
Run Code Online (Sandbox Code Playgroud)

这将创建一个<select>包含类别列表的标记.Blogger现在可以在创建/更新博客帖子时选择所需的类别.

您需要进行更改的第二个post_params方法是posts_controller:

def post_params
  params.require(:post).permit(:title, :body, :category_id)
end
Run Code Online (Sandbox Code Playgroud)

在这里,您只需将其声明:category_id为安全参数.

你现在可以查看.您的表单现在应该完全正常运行.

注意您可能还需要在帖子列表中显示类别(views/posts/index.html.erb).您可以将以下列添加到现有表:

<td><%= post.category && post.category.name %></td>
Run Code Online (Sandbox Code Playgroud)