使用新的父模型parent_id创建模型

时间:2013-08-30 07:22:17

标签: ruby-on-rails ruby

我在帖子/ _form.html.haml

中有一张照片表格

看起来像这样:

.row
  .large-9.large-centered.columns
    = simple_nested_form_for @post do |f|
      = f.input :title, label: "Title"
      = f.input :body, label: "Body", input_html: { rows: 15}
      /= link_to_add_fields "Add image", f, :photos
      = f.submit "Mentés", class: "button"

- if user_signed_in?
  = simple_form_for @post.photos.new do |f|
    %h3
      Image upload
      %i.fi-upload
    = f.input :image, input_html: { multiple: true, name: "photo[image]"}, label: false
    = f.input :post_id, val: @post.id, as: :hidden

在编辑操作中,所有照片都会使用正确的post_id保存。 但是在创建Post.new时创建动作时,它之前没有id,因此照片不会获得post_id。

不知怎的,这可以解决?也许删除这一行:

= f.input :post_id, val: @post.id, as: :hidden

并更改控制器以传递ID。

帖子控制器创建动作:

  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 action: 'show', status: :created, location: @post }
      else
        format.html { render action: 'new' }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

1 个答案:

答案 0 :(得分:3)

请尝试使用此

在新方法中使用此行

  @post = Post.new
  @post.photos.build

假设您想要在编辑模式下使用新照片 在编辑方法中使用此

  @post.photos.build

在帖子模型中你必须使用

 has_may :photos
 accepts_nested_attributes_for :photos

在表单中更新代码如下

.row
  .large-9.large-centered.columns
    = simple_nested_form_for @post do |f|
      = f.input :title, label: "Title"
      = f.input :body, label: "Body", input_html: { rows: 15}
      /= link_to_add_fields "Add image", f, :photos

      - if user_signed_in?
        = f.fields_for :photos do |photo|
          %h3
            Image upload
            %i.fi-upload
          = photo.input :image, input_html: { multiple: true}, label: false

      = f.submit "Mentés", class: "button"   

我希望这会有所帮助。

相关问题