つまり、基本的に、私のアプリには、友達(一方的なアクセス)があり、リストも所有しているユーザー(モデルユーザー)が含まれています。
ここで私が達成しようとしているのは、ユーザーの友達から選んだ「アクセサー」をリストに提供するために、新しいリストを作成するときです。
私のコードは、仮想属性に関する次のレールキャストから大きく影響を受けています。
だから、ここに私のUserとUserAccessorモデル(関連する部分だけ)が来ます:
class User < ActiveRecord::Base
has_many :lists, :dependent => :destroy
has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships
end
class UserAccessor < ActiveRecord::Base
belongs_to :accessor, :class_name => "User"
belongs_to :accessible_list, :class_name => "List"
end
マイリストモデル:
class List < ActiveRecord::Base
has_many :items
belongs_to :user
has_many :user_accessors, :foreign_key => "accessible_list_id", :dependent => :destroy
has_many :accessors, :class_name => "User", :through => :user_accessors
validates :title, :presence => true, :length => { :minimum => 1 }
attr_writer :authorized_users
after_save :add_accessors
def authorized_users
@authorized_users || self.accessors.map(&:username).join(' ')
end
private
def add_accessors
if @authorized_users
accessors = @authorized_users.split(' ').map do |username|
user = User.find_by_username(username)
if user
if self.user.inverse_friends.include? user
self.user_accessors.build(:accessor_id => user.id).accessor
end
end
end
end
end
end
リストの作成または更新に使用されるフォームは次のとおりです。
= simple_form_for [@user, @list] do |f|
= f.input :title, :label => "Titre"
= f.input :authorized_users, :label => "Authorized users", :hint => "Separated by spaces"
%p
= f.button :submit
したがって、私の問題は、アクセサーを作成/更新する方法が正確にわからないという事実に起因します。私のコードは、self.user_accessors.build(:accessor_id => user.id).accessor
正しく入力するために確実に機能していません。
私はまだレール(そして一般的にはルビー…)の初心者なので、そこに置いたものがあなたが私を助けるのに十分関連していたことを願っています!前もって感謝します!