我有User和Folder模型,每个用户都有自己的文件夹(has_many / belongs_to)。我需要做的是允许用户彼此共享一些文件夹,因此共享文件夹也成为他们的文件夹。我知道,我可以复制它们,但我正在寻找不那么蛮力的方法。
我发现this并且它太棒了,但是太旧了 - 这些方法在Rails 4中不起作用。为Rails 4重写这段代码的正确方法是什么?
应用程序/视图/布局/ application.html.erb
<head>
<title>ShareBox |<%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<%= stylesheet_link_tag "application", "redmond/jquery-ui-1.8.9.custom" %>
<%= javascript_include_tag "jquery-1.4.4.min", "jquery-ui-1.8.9.custom.min" %>
<%= javascript_include_tag "application" %>
<!-- This is for preventing CSRF attacks. -->
<%= javascript_include_tag "jquery.Rails" %>
<%= csrf_meta_tag %>
<%= yield(:head) %>
</head>
应用程序/视图/家/ index.html.erb
<div id="invitation_form" title="Invite others to share" style="display:none">
<% form_tag '/home/share' do -%>
<label for="email_addresses">Enter recipient email addresses here</label><br />
<%= text_field_tag 'email_addresses', "", :class => 'text ui-widget-content ui-corner-all'%>
<br /><br />
<label for="message">Optional message</label><br />
<%= text_area_tag 'message',"", :class => 'text ui-widget-content ui-corner-all'%>
<%= hidden_field_tag "folder_id" %>
<% end -%>
</div>
分享链接:
<%= link_to "Share", "#", :folder_id => folder.id, :folder_name => folder.name %>
资产/ javascripts.js
$(function () {
//open the invitation form when a share button is clicked
$( ".share a" )
.button()
.click(function() {
//assign this specific Share link element into a variable called "a"
var a = this;
//First, set the title of the Dialog box to display the folder name
$("#invitation_form").attr("title", "Share '" + $(a).attr("folder_name") + "' with others" );
//a hack to display the different folder names correctly
$("#ui-dialog-title-invitation_form").text("Share '" + $(a).attr("folder_name") + "' with others");
//then put the folder_id of the Share link into the hidden field "folder_id" of the invite form
$("#folder_id").val($(a).attr("folder_id"));
//Add the dialog box loading here
$( "#invitation_form" ).dialog({
height: 300,
width: 600,
modal: true,
buttons: {
//First button
"Share": function() {
//get the url to post the form data to
var post_url = $("#invitation_form form").attr("action");
//serialize the form data and post it the url with ajax
$.post(post_url,$("#invitation_form form").serialize(), null, "script");
return false;
},
//Second button
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
}
});
return false;
});
});
使用上面的代码,点击“共享”链接不会执行任何操作。对话框不会出现。我应该改变什么?
答案 0 :(得分:0)
由于多个用户可以拥有相同的文件夹,因此启用此功能的第一步应该是通过中间模型将用户和文件夹之间的关系设置为多对多。类似的东西:
class User
has_many :shared_folders
has_many :folders, through: :shared_folders
end
class Folder
has_many :shared_folders
has_many :users, through: :shared_folders
end
class SharedFolder
belongs_to :user
belongs_to :folder
end
您实施前端的方式取决于您,但创建新SharedFolder
的表单需要将user_id
和folder_id
传递给控制器。