0

我有一个类似于梦幻足球应用程序的东西,我正试图启动并运行它。现在我有一个用户模型(使用设计):

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
4

1 回答 1

0

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

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

此外,在我的 LeaguesController 中,我更改了 new 和 create 函数,因此它们现在更有意义了。

于 2015-09-16T21:06:46.473 回答