Reputation: 122
I have three model:
class Project < ActiveRecord::Base
attr_accessible :name
has_many :tickets, dependent: :delete_all
end
class Ticket < ActiveRecord::Base
belongs_to :project
attr_accessible :description, :title,:asset
has_many :assets
accepts_nested_attributes_for :assets
end
class Asset < ActiveRecord::Base
attr_accessible :title, :body
belongs_to :ticket
has_attached_file :asset
end
_form:
<%= form_for([@project,@ticket], html: { multipart: true }) do |f| %>
<p>
<%= f.label :title %>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %>
<%= f.text_area :description %>
</p>
<% number = 0 %>
<%= f.fields_for :assets do |asset| %>
<p>
<%= asset.label "File ##{number +=1}" %>
<%= asset.file_field :asset %>
</p>
<% end %>
<%= f.submit %>
<% end %>
TicketsController:
def new
@ticket = @project.tickets.build
3.times { @ticket.assets.build }
end
The problem is when I try to create new ticket for a project it shows ActiveRecord::UnknownAttributeError at /projects/1/tickets/new unknown attribute: ticket_id @ticket= id: nil, title: nil, description: nil, project_id: 1, created_at: nil, updated_at: nil, user_id: nil
From error message I can see that tickets "id" is nil(it's not yet created), so assets don't have ticket_id, so how do I get around it?
Upvotes: 1
Views: 739
Reputation: 3587
attr_accessible :ticket_id
You need to add this field as attr accessible on its model.
For nested attribuetes you also need to add project_assets as attr_accessibl/ attr_accessor
attr_accessible :project_assets
attr_accessor :project_assets
Upvotes: 1
Reputation: 540
You should use nested_form gem for assets and you have to create an attribute of ticket_id in assets database table to work association properly.
Upvotes: 0