我使用has_many:through建立了一个自我参照联盟,基本上就像这个Railscast:http://railscasts.com/episodes/163-self-referential-association所描述的那样。
某些“活动”有点像“文章”,并且有一组相关的其他活动,因此命名了连接表。这有点令人困惑......我知道。
我很难把事情做好保存。这就是我所拥有的......
activity.rb
class Activity < ActiveRecord::Base
has_many :article_activities
has_many :activities, :through => :article_activities
accepts_nested_attributes_for :activities
end
article_activity.rb
class ArticleActivity < ActiveRecord::Base
attr_accessible :article_id, :activity_id
belongs_to :activity
belongs_to :article, :class_name => "Activity"
end
articles_controller.rb
class ArticlesController < ApplicationController
def new
@activity = Activity.new
@activity.is_article = true
@user_activities = current_user.activities
end
def create
@activity = Activity.new params[:activity]
@activity.is_article = true
@activity.user = current_user
if @activity.save
redirect_to root_path, :notice => "Article created!"
else
render :action => "new"
end
end
new.html.haml
= simple_form_for @activity, :url => articles_path do |f|
/ Other fields omitted for clarity
= f.association :activities, :collection => @user_activities
因此,在提交表单后,@activity
操作中的create
具有预期的@activity.activities
。但是,在保存@activity
并重新加载记录后,@activity.activities
为空。
如何保存关联的任何想法?
答案 0 :(得分:0)
我想出了这个。我不得不在模型中添加:foreign_key作为“文章”......
class ArticleActivity < ActiveRecord::Base
attr_accessible :article_id, :activity_id
belongs_to :activity
belongs_to :article, :class_name => "Activity", :foreign_key => "article_id"
end
class Activity < ActiveRecord::Base
belongs_to :user
has_many :article_activities, :foreign_key => "article_id"
has_many :activities, :through => :article_activities
end