我有两个关于故事和类别的控制器,他们独自工作。现在我想在添加新闻时添加选择已创建的类别。我该如何连接它们以及如何使用select标签在new.html.erb中显示所有类别?
class StoriesController < ApplicationController
def index
@stories = Story.all
end
def show
@story = Story.find(params[:id])
end
def new
@story = Story.new
end
def create
@story = Story.new(params[:story])
if @story.save
redirect_to stories_path, :notice => "Your story was saved"
else
render "new"
end
end
def edit
@story = Story.find(params[:id])
end
def update
@story = Story.find(params[:id])
if @story.update_attributes(params[:story])
redirect_to stories_path, :notice => "Your story has been updated"
else
render "edit"
end
end
def destroy
@story = Story.find(params[:id])
@story.destroy
redirect_to stories_path, :notice => "Your story has been deleted"
end
end
class CategoriesController < ApplicationController
def index
@categories = Category.all
end
def new
@category = Category.new
end
def create
@category = Category.new(params[:category])
if @category.save
redirect_to categories_path, :notice => "Your category was saved"
else
render "new"
end
end
def edit
@category = Category.find(params[:id])
end
def update
@category = Category.find(params[:id])
if @category.update_attributes(params[:category])
redirect_to categories_path, :notice => "Your category has been updated"
else
render "edit"
end
end
def destroy
@category = Category.find(params[:id])
@category.destroy
redirect_to categories_path, :notice => "Your category has been deleted"
end
end
答案 0 :(得分:1)
并不是您需要将控制器连接在一起。您只需要StoriesController
来查询类别列表,并将其放入类变量中,以便视图可以使用它。
class StoriesController < ApplicationController
...
def new
@categories = Category.all
@story = Story.new
end
答案 1 :(得分:0)
您可以尝试:
# app/controllers/stories_controller.rb
def new
@categories = Category.all
@story = Story.new
end
# app/views/stories/_form.html.erb
<%= form_for @story do |f| %>
#....
<%= f.collection_select :category_id, @categories, :id, :title %>
答案 2 :(得分:0)
嘿,在控制器中你只能访问类别的标题。制作一系列cattegories标题而不是类别对象数组。
# app/controllers/stories_controller.rb
def new
@categories = Category.all.map(&:title)
@story = Story.new
end