Вопрос

I am trying to make a super simple voting system for my app. But when I try to create a new Vote model it is always set to nil. I have been looking at this for awhile and can not tell what I am doing wrong, please help.

Here is an example of a 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>]> 

When I try to create one in IRB

tyler = Vote.new
 => #<Vote id: nil, votes: 0, menu_item_id: nil, created_at: nil, updated_at: nil>

models

class MenuItem < ActiveRecord::Base
  belongs_to :menu
  belongs_to :food_item

  belongs_to :vote

class Vote < ActiveRecord::Base
  has_many :menu_items
end

controllers

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

schema

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
Это было полезно?

Решение

An instance of the Vote model will have all of its attributes set to nil by default until it is saved, at which point it will get an id and the timestamp fields (created_at and updated_at) will be set. If you want the Vote model instance to have values when it is created, use the syntax tyler = Vote.new(:votes => 3, :menu_item_id => 3) and the newly created vote will have its votes and menu_item_id attributes set.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top