【问题标题】:2 models in a form in rails 32个模型在rails 3中的形式
【发布时间】:2011-11-03 19:45:34
【问题描述】:

我对 Rails 开发非常陌生。 我正在为我的投资组合网站创建一个简单的后端。

我不确定这个问题的标题。我之前问的一个问题可能太复杂了。所以我正在简化它。

我使用 3 个模型:帖子、附件、附件类别

我有一个表格用于:

  1. 用标题、内容和类别起草帖子。

  2. 在下拉列表中显示附件类别(幻灯片、图像、视频)

  3. 上传附件。

我已经实施了第 1 步和第 2 步。

对于第 3 步:我希望这样当我最终在表单上点击提交时,附件类别 ID 会保存到附件表中。

我有以下关系:

Post.rb

class Post < ActiveRecord::Base

has_many :attachment_categories, :through => :attachments
has_many :attachments,:dependent => :destroy

accepts_nested_attributes_for :attachments
validates_presence_of :title, :content, :category

end

附件.rb

class Attachment < ActiveRecord::Base

belongs_to :post
belongs_to :attachment_category


#paperclip
has_attached_file :photo, :styles =>{

:thumb => "100x100#",
:small => "400x400>"

}

end

附件类别.rb

class AttachmentCategory < ActiveRecord::Base

has_many :posts , :through => :attachments
has_many :attachments

validates :category_name, :presence =>true

end

【问题讨论】:

    标签: ruby-on-rails-3 forms model-associations


    【解决方案1】:

    所以我已经完成了第 1 步、第 2 步和第 3 步的部分内容。

    使用我的解决方案,我只能上传一个附件。 但它有效:附件使用 post_id 和 attachment_category_id 保存到 Attachments 表中。

    以下代码来自发送到 post_controller.rb 的 _form.html.erb。 截断代码:

    .....
    
       <%= f.fields_for :attachments do |attach| %> <br>
    
       <%= attach.collection_select :attachment_category_id, AttachmentCategory.all, :id, :category_name %>
       <%= attach.file_field :photo %> <br>
    
       <% end %>
    
    .....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      相关资源
      最近更新 更多