问题
I have 2 models: News and Uploadedfile
class News < ActiveRecord::Base
has_many :uploadedfiles, as: :parent
attr_accessible :title, :content, :author
end
class Uploadedfile < ActiveRecord::Base
belongs_to :parent, polymorphic: true
has_attached_file :url
attr_accessible :url_file_name, :url_content_type, :url_file_size, :url_updated_at
end
And form:
<%= form_for(@news) do |f| %>
<div class="field">
<%= f.fields_for :uploadedfile, f.uploadedfile.new do |uf| %>
<%= uf.label :url %><br>
<%= uf.file_field :url %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
When i'm submitting form, my table uploadedfile
is not changed
where is the problem? thank you!
回答1:
I think you have nested arribute :uploadedfiles
class News < ActiveRecord::Base
has_many :uploadedfiles, as: :parent
attr_accessible :title, :content, :author, :uploadedfiles_attributes
accept_nested_attributes_for :uploadedfiles
end
And in form : change:
<%= f.fields_for :uploadedfile, f.uploadedfile.new do |uf| %>
to:
<%= f.fields_for :uploadedfiles, Uploadedfile.new do |uf| %>
回答2:
I don't think you need polymorphic association here. Here is a more readable way of doing this:
class News < ActiveRecord::Base
has_many :uploadedfiles
attr_accessible :title, :content, :author
accept_nested_attributes_for :uploadedfiles
end
class Uploadedfile < ActiveRecord::Base
belongs_to :news
has_attached_file :url
attr_accessible :url_file_name, :url_content_type, :url_file_size, :url_updated_at
end
*note that I've added accept_nested_attributes_for
And the form:
<%= form_for(@news) do |f| %>
<div class="field">
<%= f.fields_for :uploadedfiles do |uf| %>
<%= uf.label :url %><br>
<%= uf.file_field :url %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
来源:https://stackoverflow.com/questions/22611372/rails-4-paperclip-and-polymorphic-association