NoMethodError in CarController#add
undefined method `user_id=' for #<Car:0x7160c70>
RAILS_ROOT: C:/Users/Jatinder/BitNami RubyStack projects/mercedes_mod 2
add.html(用于添加汽车)
<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
答案 0 :(得分:1)
两个错误:
user_id
被声明为“inte r ger”
我认为你打算写user =
而不是user_id =
答案 1 :(得分:1)
查克是对的。您的user_id被声明为“interger”。考虑使用
t.references :user
而不是t.integer :user_id
。
同时验证您的用户模型是否使用has_one或has_many声明它与汽车模型的连接。
如果User.logged_in(session)
返回用户模型对象,则可以@car.user = User.logged_in(session)
如果不是,您的代码应该可以正常工作。
答案 2 :(得分:0)
我想知道你的用户模型中如何定义关系,可能是你没有定义用户模型中的关系,因为它无法找到user_id