我正在尝试为我的应用程序制作一个超级简单的投票系统。但是当我尝试创建一个新的投票模型时,它总是设置为零。我一直在看这个,不能告诉我做错了什么,请帮忙。
这是一个 menu_item 的示例
#<MenuItem id: 3, food_item_id: 1, menu_id: 1, created_at: "2013-09-20 03:27:45", updated_at: "2013-09-20 03:27:45", vote_id: nil>]>
当我尝试在 IRB 中创建一个
tyler = Vote.new
=> #<Vote id: nil, votes: 0, menu_item_id: nil, created_at: nil, updated_at: nil>
楷模
class MenuItem < ActiveRecord::Base
belongs_to :menu
belongs_to :food_item
belongs_to :vote
class Vote < ActiveRecord::Base
has_many :menu_items
end
控制器
class MenuItemsController < ApplicationController
def new
@menu_item = MenuItem.new
end
def index
@menu_items = MenuItem.all
end
def create
@menu_item = MenuItem.new(menu_item_params)
@vote = Vote.new
@menu_item.vote_id = @vote.id
@menu_item.save
redirect_to menus_path
end
end
class VotesController < ApplicationController
def new
@vote = Vote.new
end
def create
@vote = Vote.new
@vote.save
redirect_to menus_path
end
def vote_params
params.require(:vote).permit()
end
end
图式
ActiveRecord::Schema.define(version: 20130920030317) do
create_table "food_items", force: true do |t|
t.string "name"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "menu_items", force: true do |t|
t.integer "food_item_id"
t.integer "menu_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "vote_id"
end
create_table "menus", force: true do |t|
t.date "day"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "votes", force: true do |t|
t.integer "votes", default: 0
t.integer "menu_item_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "votes", ["menu_item_id"], name: "index_votes_on_menu_item_id"
end