感谢大家的帮助。
我是 Rails 的绝对初学者,我正在尝试学习教程。
任务如下。我有一个从脚手架构建的后期模型,只有 content:string 字段。
然后是类别模型,而不是脚手架等。这个想法是一个类别 has_many :posts 和帖子 belongs_to :category。类别具有字段名称和描述。 这很好,我理解这一点,我已将这些添加到模型中。
我也运行了迁移
rails generate migration AddCategoryToPost category:references
我现在如何让用户在发帖时添加类别。
所以事件的顺序是用户创建一个帖子,他们可以在创建帖子时添加一个类别。该类别具有用户需要定义的名称和描述。
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
如何更改帖子 Controller 的新建、创建和更新方法来实现此目的,以及表单应包含哪些内容才能创建新帖子(和类别)。
非常感谢您在高级方面的帮助,我只是不明白您将如何处理它,因为类别需要是一个“对象”并且需要添加到帖子对象(需要添加到数据库)。
最佳答案
你 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
和post_params
是这样的:
def post_params
params.require(:post).permit(:title, :body)
end
我还假设您已经定义了 Category
之间的关系和 Post
并相应地迁移数据库:
class Post < ActiveRecord::Base
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :posts
end
您需要的是添加选择 Post
的能力创建和更新时的类别。您只需在两个地方进行更改。
第一位是表格view/posts/_form.html.erb
,在 form_for
中添加以下代码片段 block :
<div class="field">
<%= f.label :category_id %>
<%= f.collection_select :category_id, Category.all, :id, :name %>
</div>
这将创建一个 <select>
带有类别列表的标签。 Blogger 现在可以在创建/更新他的博客文章时选择所需的类别。
第二个需要修改的地方是post_params
posts_controller
中的方法:
def post_params
params.require(:post).permit(:title, :body, :category_id)
end
在这里你刚刚声明了:category_id
作为安全参数。
你现在可以检查了。您的表单现在应该可以正常使用了。
注意 您可能还需要在帖子列表中显示类别 (views/posts/index.html.erb
)。您可以将以下列添加到现有表中:
<td><%= post.category && post.category.name %></td>
关于ruby-on-rails - 如何在没有类别 Controller 的情况下将类别添加到 Rails 中的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32410298/