Ryan Oliver Lanham
Ryan Oliver Lanham

Reputation: 461

Nested attributes from my form not saving

My Models:

class Group < ActiveRecord::Base
    has_many :images, :dependent => :destroy

    accepts_nested_attributes_for :images, :reject_if => lambda { |a| a[:pic].blank? }, :allow_destroy => true
end

class Image < ActiveRecord::Base
  belongs_to :group
  has_many :votes, :dependent => :destroy

  has_attached_file :pic, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :pic, content_type: /\Aimage\/.*\Z/
end

My groups controller:

def new
    @group = Group.new
    3.times {@group.images.build}
end

def create
    @group = Group.new(group_params)

    if @group.save
        redirect_to groups_path
    else
        render 'new'
    end
end

def group_params
    params.require(:group).permit(:name)
end

And my form:

<%= form_for @group, html: { multipart: true } do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name %>
    <%= f.fields_for :images do |builder| %>
        <p>
          <%= builder.label :pic %>
          <%= builder.file_field :pic %>
        </p>
    <% end %>
    <%= f.submit %>
<% end %>

So the problem is that when I submit the form, the group gets created no problem. I can find the group in the datebase, access the group attributes (the name of the group), but none of the images get saved to the database. I'm not getting an error either, so I'm not really sure what's going on. Is there something I'm missing?

Note: I'm using the paperclip gem to attach files

Upvotes: 1

Views: 50

Answers (2)

Uday kumar das
Uday kumar das

Reputation: 1613

Update your code:

def group_params    
params.require(:group).permit(:name, :images_attributes => [:pic,:_destroy])
end

Upvotes: 0

Emu
Emu

Reputation: 5905

def group_params
    params.require(:group).permit(:name, :images_attributes => [:pic])
end

You have to permit the nested parameters in your group_params.

Upvotes: 2

Related Questions