【发布时间】:2016-05-22 14:55:02
【问题描述】:
我是 Rails 新手。我有一个帖子、评论和附件控制器。因为我使用的是 FilePicker API,所以我制作了自己的 Attachments 控制器。我正在尝试构建它,以便用户可以将文件附加到帖子中,也可以根据需要将文件附加到评论中。
帖子控制器
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Your post has been created!"
redirect_to root_path
else
flash[:alert] = "Your new post couldn't be created! Please check the form."
render :new
end
end
...
private
def post_params
params.require(:post).permit(:caption, :user_id)
end
附件控制器
def create
title = params[:attachment][:title]
if Attachment.exists?(:title => title)
redirect_to attachments_path
else
@attachment = current_user.attachments.build(attachment_params)
@attachment.user_id = current_user.id
name = params[:attachment][:name]
@attachment.save
redirect_to attachments_path
end
end
...
private
def attachment_params
params.require(:attachment).permit(:title, :user_id, :name)
end
用于提交帖子的帖子视图
<%= simple_form_for(@post) do |f| %>
<div class="profile_container">
<div class="updateArea">
<%= f.text_area :caption, class: "textarea", placeholder: "Post here", label: false %>
<%= f.button :submit, "Post", disabled: true, class: "post_button", id: "post_button_padding" %>
<%# <%= f.association :user %>
</div>
</div>
上传文件的附件视图
<%= filepicker_js_include_tag %>
<%= simple_form_for @attachment, :html=> { id: 'file_stack_form' } do |f| %>
<%= f.filepicker_field :title, multiple: 'false', onchange: 'onUpload(event)', services: "CONVERT, BOX, COMPUTER, DROPBOX, EVERNOTE, FACEBOOK, GMAIL, IMAGE_SEARCH, FLICKR, GITHUB, GOOGLE_DRIVE, SKYDRIVE, URL, WEBCAM, INSTAGRAM, VIDEO, AUDIO, CLOUDDRIVE, IMGUR" %>
<%= f.submit %>
<% end %>
routes.rb
resources :posts do
resources :comments
end
resources :attachments
因此,我将 cmets 附加到帖子,并通过嵌套路由创建了该关联,并通过 has_many 和 belongs_to 创建了模型之间的关联。现在我需要对附件做同样的事情还是有另一种方法?我想要帖子/评论和附件之间的关系,以便用户可以附加文件,但我的应用程序中也会有一个单独的部分来纯粹上传/下载文件,而不需要“帖子”,这就是为什么我有一个附件的单独控制器。任何关于如何构建此功能以便用户可以将文件附加到他们的帖子的建议将不胜感激。
【问题讨论】:
标签: ruby-on-rails