Rails 4控制器对fields_for嵌套资源的操作

时间:2014-01-10 23:20:20

标签: ruby-on-rails ruby-on-rails-4 nested-forms nested-attributes 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(new和create actions)感到困惑。如何将comic_page params传递给此控制器?

  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

非常感谢!

---编辑---

在params的答案之后,我用它来创建以下创建动作:

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

1 个答案:

答案 0 :(得分:2)

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

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