我已经使用 has_many :through 建立了一个自我引用关联,基本上如该 Railscast 中所述:http ://railscasts.com/episodes/163-self-referential-association 。
一些“活动”的行为有点像“文章”,并且有一组相关的其他活动,因此连接表的命名。这有点令人困惑......我知道。
我很难让事情正确保存。这是我所拥有的...
活动.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
文章控制器.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
新的.html.haml
= simple_form_for @activity, :url => articles_path do |f|
/ Other fields omitted for clarity
= f.association :activities, :collection => @user_activities
因此,在提交表单后,@activity
actioncreate
中有预期的@activity.activities
. 但是,在保存@activity
并重新加载记录时, @activity.activities
它是空的。
任何想法如何保存关联?