Rails 4 个控制器操作用于fields_for嵌套资源



我试图理解Rails的field_for,特别是嵌套资源的控制器应该是什么。 我的问题是,当我通过漫画形式创建带有漫画页面的漫画时,页面的图像不会保存。

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

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参数传递给此控制器???

  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

您需要在控制器的comic_params部分中允许要保存的comic_pages中的字段

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

相关内容

  • 没有找到相关文章

最新更新