Search code examples
ruby-on-railsassociationscontrollers

NoMethodError in Characters#new


I am new to Rails.I am creating a Rails project in which Product and Character are the models.I have the following Questions.

Q1. Is the given association between the two models is right?

class Product < ActiveRecord::Base

has_many :characters

end


class Character < ActiveRecord::Base

belongs_to :product

end

Q2. I created a link to add new character in the 'show' page of the products such if we click add new character it should display a 'new' page of characters in which i should have a dropdown list of character names(i.e., height,width,weight and color) but it is not.

It is showing NoMethodError in Characters#new error.

Error raised in the below line of my characters/new file.

 collection_select(:product, :c_id, @character, :id, :name) 

Note: I had created the values for name attribute as height,weight,width,color in the characters before migrating it.

Q3. If that works(i.e., Q2), i want to show the character name and value in the 'show page of products.For this how can i redirect to 'show' page of products..?

My characterscontroller for new,show and create:

def show

@product = Product.find(params[:id])

  @character = Character.find(params[:id])

end



def new

 @character = Character.new(params[:character])

 @product = Product.find(params[:id])

end


def create

  @character = Character.new(params[:character])


    if @character.save

 redirect_to :action => 'show', :id => @product.id

else

render :action => 'new'

end

end

Well now, after entering the values for the character in the characters/new and clicking create button it is trowing the following error

ActiveRecord::RecordNotFound in ProductsController#show 
     Couldn't find Product without an ID

I want to show the character name and value in the products/show. the above error is stopping me to do that..

My show method in productscontroller:

def show

@product = Product.find(params[:id])

@character = Character.find(:all)

end

Solution

    1. The classes are correct to reflect the One-to-Many Relationship.
    2. Problem with NoMethodError appears to be related to how you setup model, routes, controller & view.

    Lets say in your model you have attr_accessible :id, :name (I don't see this in your model and this is why the error!)

    In character controller you need something like this:

    def new
         @character = Character.new
         @product   = Product.find(params[:character_id])
    end
    

    In the view(app/views/products/new.html.erb), you can add the link for new characters as: <% link_to "Character", new_product_character_path(product) %>

    the above assumes, you set your routes correct by having following in your config/routes.rb: "resources :products" "resources :characters"