Вопрос

I have a few models...User model, A collection model and an inspiration model...

The collection model has_one inspiration

has_one :inspiration, :dependent => :destroy
belongs_to :user

the inspiration model belongs to a collection

belongs_to :collection
belongs_to :user

here are my routes

resources :collections do
  resources :inspiration
end

Here is my InspirationController (it is not plural)

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

My view for inspiration is also singular (not inspirations)

In all the time I've been using Rails which isnt too terribly long I haven't had to use the has_one association and now I'm coming up with some errors...

When i view the pages I either get one of two errors...

One is an undefined method of inspiration which comes from the second line of each action in the InspirationController...the other says an undefined method COUNT, because I have an if statement in the view

if @collection.inspiration.count > 0 
   foobar foobar
end 

In the rails console, when i try to find the count of the inspirations of a specific collection, i can see that it isn't even performing the proper query....

can anyone shed some light on this problem or point me to a good resource to read up on this type of association...thank you in advance

one thing to point out which i did different than I normally do for has_many associations... 1. i used the singular "inspiration" in place of the plural "inspirations" in quite a few places including the routes, view, and controller.

Here is an EDIT when trying to create a new inspiration, I get the following error

undefined method `inspiration'

which points to the new action

@user = current_user
@collection = @user.collections.find(params[:collection_id])
@inspiration = @collection.**inspiration**.new

the word inspiration in between the stars in where the problem is occuring

cheers, Justin

Это было полезно?

Решение

Since collection has_one inspiration, @collection.inspiration return an inspiration object, not a collection of inspiration (did you have to call your model collection, now I'm mumbling :P). Instead do:

if @collection.inspiration
  foobar foobar
end

also you can't do @inspiration = @collection.inspiration.new as inspiration is nil. Instead do:

@inspiration = @collection.build_inspiration
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top