我有三个模特叫妈妈,孩子和最爱。
class Mom < ActiveRecord::Base
has_many :kids
has_many :favorites
class Kid < ActiveRecord::Base
belongs_to :mom
belongs_to :user
class Favorite < ActiveRecord::Base
belongs_to :mom
belongs_to :user
我正试着喜欢一个母亲:
class KidsController < ApplicationController
show
@kid = Kid.find(params[:id])
end
# link to favorite kid's mom at kids/show
link_to({ controller: 'favorites', action: 'create', id: @kid.mom.id }, { method: :post })
现在我遇到的问题是,当我试图在我的收藏夹控制器中使用此代码创建它时:
class FavoritesController < ApplicationController
def create
@mom = Mom.find(params[:id])
@favorites = current_user.favorites.build(params[:favorites])
@favorites.mom_id = @kid.mom.id
if @favorites.save
redirect_to :back, notice: "#{@favorite.mom.name.titleize} is one of your favorites now."
else
redirect_to :back
end
end
这让我犯了个错误:
undefined method `mom' for nil:NilClass
从这条线上我相信:
kids/show
这是为什么?
最佳答案
您可能需要使用accepts_nested_attributes_for
退房this railscasts
关于ruby-on-rails - 如何从link_to创建没有直接关联的资源?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24577749/