我有一个小示例应用程序,其中有 3 个模型:成员、组和订阅。这个想法是成员可以订阅组。
class Member < ActiveRecord::Base
has_many :subscriptions, dependent: :delete_all
has_many :groups, through: :subscriptions
attr_accessible :email
validates :email, presence: true
end
class Group < ActiveRecord::Base
has_many :subscriptions, dependent: :delete_all
has_many :members, through: :subscriptions
accepts_nested_attributes_for :subscriptions
attr_accessible :name, :subscriptions_attributes
validates :name, presence: true, uniqueness: true
end
class Subscription < ActiveRecord::Base
belongs_to :group
belongs_to :member
attr_accessible :group_id, :introduction
validates :group_id, presence: true
validates :introduction, presence: true
end
我正在尝试为新组创建一个表单,并将introduction
属性嵌套在其中。
我的控制器方法:
def new
@group = Group.new
@group.subscriptions.build
end
def create
@member = Member.first
@group = @member.groups.build(params[:group])
if @group.save
flash[:success] = "Saved"
redirect_to group_path(@group)
else
render :new
end
end
但它不起作用。它抛出错误group_id can't be blank
。所以我不知道如何将新组分配给订阅。
此外,member_id 被创建为 nil。但是正如您所看到的,我正在从@member
变量创建组,所以我认为它应该被初始化,但它没有。
谁能给我看灯?
您可以在此处查看示例应用程序:https ://github.com/idavemm/nested_form