Rails4,cocoon,嵌套表单和has_many通过

时间:2015-09-16 16:36:54

标签: ruby-on-rails devise cocoon-gem simple-form-for

我有一个类似幻想足球应用程序的东西,我正在尝试起床和运行。现在我有一个用户模型(使用Devise):

class User < ActiveRecord::Base
has_many :league_memberships
has_many :leagues, through: :league_memberships

accepts_nested_attributes_for :league_memberships

有一个联盟模式:

class League < ActiveRecord::Base
    has_many :league_memberships
    has_many :users, through: :league_memberships    

    accepts_nested_attributes_for :league_memberships

还有LeagueMembership模型:

class LeagueMembership < ActiveRecord::Base
    belongs_to  :league
    belongs_to  :user

    accepts_nested_attributes_for :user
    accepts_nested_attributes_for :league

用户可以是许多联盟的成员,联盟可以有很多用户。

因此,当用户想要创建联盟时,他/她会这样做,然后可以编辑联盟以添加/删除其他用户。这是编辑联盟的表格:

= simple_form_for @league do |f|
.panel-body
    .row
        .col-md-4
            = f.input :name, input_html: { class: 'form-control' }
            = f.input :description, input_html: { class: 'form-control' }

        .col-md-8
            %h3 League Members
            = f.simple_fields_for :league_memberships do |membership|
                = render 'membership_fields', f: membership
            = link_to_add_association 'Add Member', f, :league_memberships, class: 'btn btn-default'

= f.button :submit, class: 'btn btn-primary'

“membership_fields”部分:

.nested-fields.col-md-8
    = f.association :user, collection: User.order(:username), prompt: 'Choose a new member'
    = link_to_remove_association "Remove member", f, class: "btn btn-default"

当我尝试编辑现有联盟时,它会抛出MissingTemplate错误,并说它正在寻找另一个名为_league_membership_fields的部分。

我在这里缺少什么?我已经查看了大量的教程,要么我在某个地方有错字,要么就我的数据建模而言,我完全错过了这条船。

编辑:这是导致错误的行:

= link_to_add_association 'Add Member', f, :league_memberships, class: 'btn btn-default'

现在看起来我也无法建立新的联赛。这是LeaguesController:

class LeaguesController < ApplicationController

def new
    @leauge = League.new
    @league.league_memberships.build
end

def create
    @league = League.new(league_params)
    @league.league_memberships.build(user_id: current_user.id)
    if @league.save
        redirect_to @league
    else
        render 'new'
    end
end

def index
    @leagues = Leagues.paginate(page: params[:page])
end

def show
    @league = League.find(params[:id])
end

def edit 
    @league = League.find(params[:id])
end

def update
    @league = League.find(params[:id])
    if @league.update_attributes(league_params)
        flash[:success] = "League Updated!"
        redirect_to @league
    else
        render 'edit'
    end
end

private

def league_params
    params.require(:league).permit(
        :name, :description,
        users_attributes: [:id, :username, :name],
        league_memberships_attributes: [:league_id, :user_id]
    )
end

end

1 个答案:

答案 0 :(得分:0)

我想我设法解决了我的问题。

错误是对的。根据我上面的代码,表单试图加载错误的部分。我添加了另一个名为_league_membership_fields的部分,就像它应该的那样,现在它可以工作。

另外,在我的LeaguesController中,我改变了我的新功能和创建功能,所以现在它们更有意义了。