我得到在CarController#错误NoMethodError添加
问题描述:
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
答
两个错误:
user_id
被声明为 “INTE [R蒙古包”我想你的意思是写
user =
而不是user_id =
答
我想知道如何在您的用户模型中定义的关系,可能是你没有定义的用户模型,由于关系这它不是能找到USER_ID
答
查克是正确的。您的user_id被声明为“整合者”。考虑使用 t.references :user
而不是t.integer :user_id
。
还要验证您的用户模型是否使用has_one或has_many声明了它与汽车模型的连接。
如果User.logged_in(session)
返回一个用户模型对象,你可以做@car.user = User.logged_in(session)
如果不是你的代码应该可以正常工作。
你的汽车模型和移植是什么样的? – 2011-05-18 20:55:24
你能发布你的数据库模式吗?该错误通常意味着没有user_id字段。 – Tom 2011-05-18 20:56:03
@ jared hales @Tom我现在已经发布了 – 2011-05-18 21:20:50