Dudo
Dudo

Reputation: 4169

NameError with a has_many_through table

class User < ActiveRecord::Base
  has_many :ties, dependent: :destroy
  has_many :albums, through: :ties
end

class Album < ActiveRecord::Base
  has_many :ties, dependent: :destroy
  has_many :users, through: :ties
end

class Tie < ActiveRecord::Base
  belongs_to :user
  belongs_to :album, dependent: :destroy
end

K... so, When trying to create an album, from the AlbumsController#Create action:

def create
  @album = current_user.albums.build(params[:album]) #error is on this line
  if @album.save
    flash[:success] = "#{@album.description} created!"
    redirect_to @album
  else
    flash[:error] = 'Looks like something was invalid with that album. Try again.'
    redirect_to albums_path
  end
end

I'm getting uninitialized constant User::Ty. I think rails is confusing Tie with Ty. Any idea? Can I force certain names from en.yml?

Upvotes: 1

Views: 84

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107738

This is indeed because Rails is trying to singularize ties to derive the class name. The best way around this would be to define a new inflection rule for this. In Rails 4 you would do this:

ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.singular /^ties$/i, 'tie'
end

But in Rails 3 you would do this:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.singular /^ties$/i, 'tie'
end

Upvotes: 3

Related Questions