2013-04-26 3 views
1

У меня довольно красивая ошибка при попытке сохранить запись (с использованием Rails 4, Ruby 2.0.0).Запись рельсов не сохраняется

Это то, что происходит.

2.0.0p0 :001 > Startup 
=> Startup(id: integer, name: string, url: string, founded: date, mal: boolean, 
      created_at: datetime, updated_at: datetime, creator: string, 
      description: text, category: text) 

2.0.0p0 :002 > @s = Startup.new(:name => "New Startup", 
           :url => "http://newstartup.com", 
           :founded => Date.today, 
           :mal => false, 
           :creator => "127.0.0.1", 
           :description => "This is a description", 
           :category => ["","Sports"]) 
=> #<Startup id: nil, name: "New Startup", url: "http://newstartup.com", founded: "2013-04-25", mal: false, created_at: nil, updated_at: nil, creator: "127.0.0.1", description: "This is a description", category: ["", "Sports"]> 

2.0.0p0 :003 > @s.save 
    (0.2ms) BEGIN 
    (0.3ms) ROLLBACK 
=> false 

Это моя модель:

class Startup < ActiveRecord::Base 
    before_validation(:on => :create) do 
    self.mal = false 
    end 

    attr_accessible :name, :url, :description, :category, :creator, :mal, :founded 
end 

схема:

create_table "startups", force: true do |t| 
    t.string "name" 
    t.string "url" 
    t.date  "founded" 
    t.boolean "mal" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "creator" 
    t.text  "description" 
    t.text  "category" 
end 

и контроллер:

class StartupsController < ApplicationController 
    before_action :set_startup, only: [:show, :edit, :update, :destroy] 
    before_create :set_creator 

    # GET /startups 
    # GET /startups.json 
    def index 
    @startups = Startup.all 
    end 

    def land 
    @startup = Startup.new 
    @resource = User.new 
    @devise_mapping = Devise.mappings[:user] 
    end 

    # GET /startups/1 
    # GET /startups/1.json 
    def show 
    end 

    # GET /startups/new 
    def new 
    @startup = Startup.new 
    end 

    # GET /startups/1/edit 
    def edit 
    end 

    # POST /startups 
    # POST /startups.json 
    def create 
    @startup = Startup.new(startup_params) 

    respond_to do |format| 
     if @startup.save 
     format.html { redirect_to @startup, notice: 'Startup was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @startup } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @startup.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /startups/1 
    # PATCH/PUT /startups/1.json 
    def update 
    respond_to do |format| 
     if @startup.update(startup_params) 
     format.html { redirect_to @startup, notice: 'Startup was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: 'edit' } 
     format.json { render json: @startup.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /startups/1 
    # DELETE /startups/1.json 
    def destroy 
    @startup.destroy 
    respond_to do |format| 
     format.html { redirect_to startups_url } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_startup 
     @startup = Startup.find(params[:id]) 
    end 

    def set_creator 
     @startup.creator = request.remote_ip 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def startup_params 
     params.require(:startup).permit(:name, :url, :added, :founded, :mal, :creator, :description, {:category => []}) 
    end 
end 

Я только начал получать эту проблему, когда я хотел переключить Startup.category от стринга g в список строк.

Что я делаю неправильно или где могу найти дополнительную информацию об ошибке?

+0

Вы пытаетесь сохранить массив в текстовом столбце. Разве это не должно быть смоделировано и отображено как ассоциация? –

+0

@grotori Я бы хотел избежать другой таблицы, если это возможно, но я думал, что массивы можно сохранить с помощью сильных_параметров https: //github.com/rails/strong_parameters ... не уверены, что текстовый столбец прав, но я не знаю, что такое –

+0

Кроме того, если я изменяю 'Startup.category' строку, те же ошибки сохраняются. –

ответ

10

whateverModel.save не вызывает никаких исключений, но возвращает true (модель сохранена) или false. Если вы звоните save, create или update_attributes (без взрыва) или valid? ваша модель будет разоблачить errors свойства, из консоли:

puts @s.errors.messages.inspect 

Обновление:

Вашего последнее (и только) выражение в вашем before_validation возвращается false что означает, что транзакция будет прервана, попробуйте:

self.mal=false 
true 
+0

'serialize' устарел в Rails 4, я думаю. Я попробовал эту попытку некоторое время назад :(Также, '2.0.0p0: 006> puts @ s.errors.messages.inspect {} => nil' –

+0

Но' 2.0.0p0: 008> @ s.valid? => false ', но в ошибках ничего не отображается ... –

+0

Посмотрите на обновление, надеюсь, это поможет – Jef

Смежные вопросы