嗨,我目前正在开发我的第一个 Rails 项目,这是一个供用户制作专辑和上传图片的网站。我的应用程序中安装了注册、登录和加好友功能。我正在努力做到这一点,以便在相册创建表单中,您可以看到您的朋友列表并选择您想要与谁共享相册访问权限(这意味着您选择的任何人也将成为其中的一部分@album.users
。我正在计划关于使用复选框(我想不出更好的方法)进行此选择。但是,我不确定如何将friendship
模型与专辑/新表单链接起来。这就是我的表单的样子:
专辑/new.html.erb
<%= form_for ([@user, @album]), :html => { :id => "uploadform", :multipart => true } do |f| %>
<div class="formholder">
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.check_box :friends %>
<%= f.label :description %>
<%= f.text_area :description %>
<br>
<%=f.submit %>
</div>
<% end %>
第 6 行出现错误(
<%= f.check_box :friends %>
错误:
undefined method 'friends' for #<Album:0x007fa3a4a8abc0>
我可以理解为什么,但我不知道如何解决它。我有典型的友谊加入模型来添加朋友,我希望能够看到所有朋友的列表并选择他们。我认为接下来的步骤是@album.users << @user.friendships.find_by_name(params[:friends])
在相册控制器的创建操作中添加类似的内容,但我不知道如何循环遍历只为朋友返回一个参数的表单?
这是我的文件:
相册控制器创建动作:
def create
@user = User.find(params[:user_id])
@album = @user.albums.build(params[:album])
# not so sure about the following line.
@album.users << @user.friendships.find_by_name(params[:friends])
respond_to do |format|
if @user.save
format.html { redirect_to user_album_path(@user, @album), notice: 'Album was successfully created.' }
format.json { render json: @album, status: :created, location: @album}
else
format.html { render action: "new" }
format.json { render json: @album.errors, status: :unprocessable_entity }
end
end
end
专辑模特
class Album < ActiveRecord::Base
attr_accessible :name, :description
validates_presence_of :name
has_many :album_users
has_many :users, :through => :album_user
has_many :photos
end
用户模型
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :name, :password, :password_confirmation
validates_presence_of :password, :on => :create
validates_format_of :name, :with => /[A-Za-z]+/, :on => :create
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validates_length_of :password, :minimum => 5, :on => :create
has_many :album_users
has_many :albums, :through => :album_users
accepts_nested_attributes_for :albums
has_many :friendships
has_many :friends, :through => :friendships
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
private
def create_remember_token
self.remember_token = SecureRandom.urlsafe_base64
end
结尾
album_user 模型(连接表以在有很多用户的相册和有很多相册的用户之间建立多对多关系)
class AlbumUser < ActiveRecord::Base
belongs_to :album
belongs_to :user
end
友谊模型
class Friendship < ActiveRecord::Base
attr_accessible :friend_id
belongs_to :user
belongs_to :friend, :class_name => "User"
end
如果您需要更多信息,请告诉我!!提前致谢!!!