CarController中的NoMethodError#为#<car:0x71451d8> </car:0x71451d8>添加未定义的方法`user_id ='

时间:2011-05-18 22:08:15

标签: ruby-on-rails ruby

NoMethodError in CarController#add

undefined method `user_id=' for #<Car:0x7160c70>
RAILS_ROOT: C:/Users/Jatinder/BitNami RubyStack projects/mercedes_mod 2
add.html (for adding car)

add.html in / views / car

<h1>Ask a Question or Discuss Your Car</h1>
<%= error_messages_for :car %>
<br>
<p>You can ask anything related to cars even if its not a Mercedes!</p>
<% form_for :car do |f| %>

  <p>
    <%= f.label :name, "Title of Question" %>
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :description, "Describe Your Question" %>
    <%= f.text_area :description %>
  </p>
  <p>
    <%= f.submit "Add" %>
  </p>
<% end %>

在car_controller.rb中添加def:

def add 
      @title = "Ask a New Question"
    if request.post?
       @car = Car.new(params[:car])
       @car.user_id = User.logged_in(session).id
    if @car.save
        flash[:notice] = "Car #{@car.name} added!"
        redirect_to :controller => :car, :action => :index
      end
    end
  end

car.rb型号:

class Car < ActiveRecord::Base
    belongs_to :user
    belongs_to :subject
  validates_presence_of :name, :description
end

的routes.rb

map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
  map.resources :car, :users => { :delete => :get }
  map.root :controller => "main"
  map.root :controller => "car", :action => "destroy"
end

create_cars migration:

class CreateCars < ActiveRecord::Migration
  def self.up
    create_table :cars do |t|
      t.interger :user_id
      t.string :name
      t.string :description

      t.timestamps
    end
  end

  def self.down
    drop_table :cars
  end
end

2 个答案:

答案 0 :(得分:0)

您的迁移有拼写错误。您t.integer上应该有t.interger,而不是:user_id。此外,请确保在运行应用程序之前在控制台中运行rake db:migrate

答案 1 :(得分:0)

您的迁移已被破坏:

t.interger :user_id

您正在寻找整数