谢谢大家对我们的帮助。
我是rails的绝对初学者,我正在努力完成一个教程。
任务如下。我有一个从脚手架构建的帖子模型,只有内容:字符串字段。
然后是一个类别模型,而不是脚手架等。这个想法是一个类别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
如何更改帖子控制器的新方法,创建方法和更新方法以实现此目的,从而表格应包含什么来创建新帖子(和类别)。
非常感谢你在高级方面提供的帮助,我只是不明白你会怎么做,因为类别需要是一个'对象',需要添加到一个帖子对象(需要添加到数据库)。
答案 0 :(得分: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
和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
块中添加以下代码段:
<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>