我真的处于压力之下并对Rails全新。项目在两天内到期。
我在Rails控制台上搜索了在我的数据库user = user.find(1)
中输入的用户并返回。
用户has_many食谱 食谱属于用户....分别在用户和食谱模型中定义。
我收到了错误。
用户的未定义方法“食谱”?
这就是我创建用户的方式
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.integer "position"
t.boolean "visible", :default => false
t.string "restaurant_name", :limit => 25
t.string "username", :limit => 25
t.string "password", :limit => 50
t.string "hashed_email", :default => "", :null => false
t.string "address1", :limit => 80
t.string "address2", :limit => 80
t.string "address3", :limit => 80
t.string "county", :limit => 40
t.string "telephone", :limit => 40
t.text "web address", :limit => 60
t.string "photo_path", :limit => 100
t.text "description", :limit => 2000
t.text "salt", :string, :limit => 50
t.timestamps
end
end
def self.down
drop_table :users
end
end
配方
class CreateRecipes < ActiveRecord::Migration
def self.up
create_table :recipes do |t|
t.integer "user_id"
t.string "recipe_name", :limit => 100
t.integer "greedy_type", :default => 0
t.string "photo_path", :limit => 40
t.text "description", :limit => 400
t.text "recipe", :limit => 4000
t.integer "ingredient1", :limit => 40
t.integer "ingredient2", :limit => 40
t.integer "ingredient3", :limit => 40
t.integer "ingredient4", :limit => 40
t.string "permalink"
t.integer "position"
t.boolean "visible", :default => false
t.timestamps
end
add_index("recipes", "user_id")
add_index("recipes", "permalink")
end
def self.down
drop_table :recipes
end
end
users.rb的
class Users < ActiveRecord::Base
has_many :recipes
end
recipe.rb
class Recipes < ActiveRecord::Base
belongs_to :users
has_many :restaurants
end
ERROR
irb(main):005:0> users.recipe
NoMethodError: undefined method `recipe' for #<Users:0x599ebc0>
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activemodel-3.0.9/lib/active_model/attribute_methods.rb:
392:in `method_missing'
from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/activerecord-3.0.9/lib/active_record/attribute_methods.r
b:46:in `method_missing'
答案 0 :(得分:7)
如果User
has_many recipes
,为什么要为recipe_id
添加字段user
?您应该将user_id
字段添加到Recipe
类表中。创建recipe
后,只需存储user_id
,这就是您所需要的。干杯!
答案 1 :(得分:2)
因为用户有很多食谱,
你必须写一些类似于获得第一批用户的食谱......
recipe = user.recipes.first
并将user_id存储在配方表中。