2011-05-18 61 views
0
NoMethodError in CarController#add 

undefined method `user_id=' for #<Car:0x7160c70> 
RAILS_ROOT: C:/Users/Jatinder/BitNami RubyStack projects/mercedes_mod 2 

add.html(用於增加汽車)我得到在CarController#錯誤NoMethodError添加

<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 %> 

DEF加入car_controller.rb:

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遷移:

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 
+0

你的汽車模型和移植是什麼樣的? – 2011-05-18 20:55:24

+0

你能發佈你的數據庫模式嗎?該錯誤通常意味着沒有user_id字段。 – Tom 2011-05-18 20:56:03

+0

@ jared hales @Tom我現在已經發布了 – 2011-05-18 21:20:50

回答

1

兩個錯誤:

  1. user_id被聲明爲 「INTE [R蒙古包」

  2. 我想你的意思是寫user =而不是user_id =

0

我想知道如何在您的用戶模型中定義的關係,可能是你沒有定義的用戶模型,由於關係這它不是能找到USER_ID

1

查克是正確的。您的user_id被聲明爲「整合者」。考慮使用 t.references :user 而不是t.integer :user_id

還要驗證您的用戶模型是否使用has_one或has_many聲明瞭它與汽車模型的連接。

如果User.logged_in(session)返回一個用戶模型對象,你可以做@car.user = User.logged_in(session)如果不是你的代碼應該可以正常工作。

相關問題