2 个模型采用导轨 3 形式
我对 Rails 开发非常陌生。 我正在为我的投资组合网站创建一个简单的后端。
我不确定这个问题的标题。我之前问的一个问题可能太复杂了。所以我正在简化它。
我使用 3 个模型:帖子、附件、Attachment_Category
我有一个表单,用于:
起草包含标题、内容和类别的帖子。
在下拉列表中显示附件类别(幻灯片、图像、视频)
上传附件。
我已经实现了步骤 1 和 2。
对于步骤 3:我希望当我最终点击表单上的“提交”时,attachment_category_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
Attachment.rb
class Attachment < ActiveRecord::Base
belongs_to :post
belongs_to :attachment_category
#paperclip
has_attached_file :photo, :styles =>{
:thumb => "100x100#",
:small => "400x400>"
}
end
Attachment_category.rb
class AttachmentCategory < ActiveRecord::Base
has_many :posts , :through => :attachments
has_many :attachments
validates :category_name, :presence =>true
end
I am very new to rails development.
I am creating a simple backend for my portfolio site.
I am not sure about the title of this question. A previous question I asked maybe too convoluted. So I am simplifying it.
Im using 3 models: Post, Attachment, Attachment_Category
I have a form that I use to:
Draft the post with a title, content and a category.
Display attachment categories in a drop down (slideshow, image, video)
Upload the attachment(s).
I have implemented steps 1 and 2.
For step 3: I want it so that when I finally hit submit on the form, the attachment_category_id is saved to the attachment table.
I have the following relationships:
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
Attachment.rb
class Attachment < ActiveRecord::Base
belongs_to :post
belongs_to :attachment_category
#paperclip
has_attached_file :photo, :styles =>{
:thumb => "100x100#",
:small => "400x400>"
}
end
Attachment_category.rb
class AttachmentCategory < ActiveRecord::Base
has_many :posts , :through => :attachments
has_many :attachments
validates :category_name, :presence =>true
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样我就完成了步骤 1、步骤 2 和步骤 3 的一部分。
通过我的解决方案,我只能上传一个附件。
但它有效:附件使用 post_id 和 Attachment_category_id 保存到 Attachments 表中。
以下代码来自 _form.html.erb,它被发送到 post_controller.rb。
截断的代码:
So I have accomplished Steps 1, parts of step 2 and step 3.
With my solution, I am able to upload just one attachment.
But it works: The attachment gets saved to the Attachments table with the post_id and the attachment_category_id.
The following code is from _form.html.erb which gets sent to post_controller.rb.
Truncated code: