Rails 4, Paperclip and polymorphic association

。_饼干妹妹 提交于 2020-01-03 05:01:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!