我有一些models...User模型,一个集合模型和一个灵感模型.
集合模型has_one灵感
has_one :inspiration, :dependent => :destroy
belongs_to :user灵感模型属于一个集合。
belongs_to :collection
belongs_to :user这是我的路线
resources :collections do
resources :inspiration
end这是我的InspirationController (不是复数)
def index
@collection = Collection.find(params[:collection_id])
@inspiration = @collection.inspiration
end
def new
if signed_in? && current_user == @collection.user
@user = current_user
@collection = @user.collections.find(params[:collection_id])
@inspiration = @collection.inspiration.new
elsif signed_in? && current_user != @collection.user
flash[:error] = "That's not your collection."
redirect_to root_url
else
flash[:error] = "Please sign in."
redirect_to login_url
end
end我对灵感的看法也是单数的(不是灵感)。
在所有的时间里,我一直在使用Rails,时间不长,我没有使用has_one关联,现在我出现了一些错误.
当我查看页面时,我会发现两个错误中的一个.
一种是来自InspirationController...the中每个动作的第二行的未定义的灵感方法,另一种是未定义的方法计数,因为我在视图中有一个if语句。
if @collection.inspiration.count > 0
foobar foobar
end 在rails控制台中,当我试图查找特定集合的灵感计数时,我可以看到它甚至没有执行正确的查询.
有人能说明一下这个问题吗?或者告诉我一个很好的资源,可以提前阅读这类association...thank你。
有一点要指出的是,我所做的与我通常为has_many协会做的不同.1.在很多地方,包括路线、视图和控制器,我用单数的“灵感”代替复数的“灵感”。
下面是一个编辑,当我尝试创建一个新的灵感时,我会得到以下错误
undefined method `inspiration'它指向新的行动
@user = current_user
@collection = @user.collections.find(params[:collection_id])
@inspiration = @collection.**inspiration**.new灵感这个词出现在问题所在的星星之间
干杯,贾斯汀
发布于 2013-09-19 19:24:01
由于集合has_one inspiration,@collection.inspiration返回一个inspiration对象,而不是一个灵感集合(您是否必须调用您的模型集合,现在我在咕哝:P)。相反,请做:
if @collection.inspiration
foobar foobar
end而且你不能做@inspiration = @collection.inspiration.new,因为灵感是零的。相反,请做:
@inspiration = @collection.build_inspirationhttps://stackoverflow.com/questions/18903127
复制相似问题