gpt4 book ai didi

ruby-on-rails - fields_for 嵌套资源的 Rails 4 Controller 操作

转载 作者:行者123 更新时间:2023-12-04 07:39:44 25 4
gpt4 key购买 nike

我正在尝试了解 Rails 的 field_for,特别是嵌套资源 Controller 中应该包含哪些内容。我的问题是,当我通过 Comic 表单创建带有漫画页面的漫画时,页面的图像未保存。

我有用户、漫画和漫画页面。以下是模型:

class User < ActiveRecord::Base
has_many :comics
has_many :comic_pages, through: :comics
end

class Comic < ActiveRecord::Base
belongs_to :user
has_many :comic_pages, :dependent => :destroy
accepts_nested_attributes_for :comic_pages
end

class ComicPage < ActiveRecord::Base
belongs_to :comic
end

这是 Comic 的表单,我还想在其中添加 comic_pages:

 <%= form_for ([@user, @comic]) do |f| %>
<%= f.text_field :title %>
<%= f.fields_for :comic_pages do |comic_page| %>
<%= comic_page.file_field :comic_page_image %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

我对 comics_controller(新建和创建操作)感到困惑。我怎样才能将 comic_page 参数传递给这个 Controller ???

  def new
@user = current_user
@comic = @user.comics.new
@comic.comic_pages.build
end

def create
@user = current_user
@comic = @user.comics.new(comic_params)
@comic.comic_pages.build

respond_to do |format|
if @comic.save
format.html { redirect_to @user, notice: 'Comic was successfully created.' }
format.json { render action: 'show', status: :created, location: @user }
else
format.html { render action: 'new' }
format.json { render json: @comic.errors, status: :unprocessable_entity }
end
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_comic
@comic = Comic.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def comic_params
params.require(:comic).permit(:title, :synopsis)
end

def comic_page_params
params.require(:comic_page).permit(:comic_page_image, :comic_image_file_name)
end

非常感谢!

--- 编辑 ---

在参数的答案之后,我用它来创建以下创建操作:

def create
@user = current_user
@comic = @user.comics.new(comic_params)

i = 0
until i = 1
@comic_page = @comic.comic_pages.new(comic_params[:comic_pages_attributes]["#{i}"])
@comic_page.save
i += 1
end

respond_to do |format|
if @comic.save
...
end
end
end

最佳答案

您需要在 Controller 的comic_params 部分允许comic_pages 中要保存的那些字段

params.require(:comic).permit(:title, :synopsis, comic_pages_attributes: [:comic_page_image])

关于ruby-on-rails - fields_for 嵌套资源的 Rails 4 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21056290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com