Rails:项目未保存到数据库(使用嵌套资源进行路由)

时间:2018-01-25 00:23:42

标签: ruby-on-rails ruby

尝试使用Rails中的嵌套资源创建新对象时遇到了问题。我的路由设置为:

resources :coins do
  resources :questions
  resources :events
end

当我尝试创建新事件时,它不会保存。添加! event.save 给了我一个错误,上面写着" 验证失败:硬币必须存在"。

我没有为硬币设置验证(至少在事件模型中,如果这是它所指的那样)。检查日志文件显示以下内容,据我所知,显示选择了正确的硬币:

Started GET "/coins/1/events/new" for 127.0.0.1 at 2018-01-24 18:52:19 -0500
Processing by EventsController#new as HTML
  Parameters: {"coin_id"=>"1"}
  [1m[36mCoin Load (0.1ms)[0m  [1m[34mSELECT  "coins".* FROM "coins" WHERE "coins"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mUser Load (0.2ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  Rendering events/new.html.erb within layouts/application
  Rendered events/new.html.erb within layouts/application (3.9ms)
  Rendered layouts/_rails_defaults.html.erb (34.8ms)
  Rendered layouts/_shim.html.erb (0.6ms)
  Rendered layouts/_header.html.erb (6.2ms)
Completed 200 OK in 67ms (Views: 62.3ms | ActiveRecord: 0.3ms)


Started POST "/coins/1/events" for 127.0.0.1 at 2018-01-24 18:54:46 -0500
Processing by EventsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"dAXQ3uwxR2IN2rbAYD//gulHebIOdZWFPYCKnxcUKTuV4QnUp+SZYHMpZUsGOgEXQjOAnhFUO9MpJkIIAKcQlQ==", "event"=>{"content"=>"LKNA", "link"=>"asd"}, "commit"=>"Submit", "coin_id"=>"1"}
  [1m[36mCoin Load (0.2ms)[0m  [1m[34mSELECT  "coins".* FROM "coins" WHERE "coins"."id" = ? LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mUser Load (0.2ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[35m (0.1ms)[0m  [1m[36mbegin transaction[0m
  [1m[35m (0.0ms)[0m  [1m[31mrollback transaction[0m
Completed 401 Unauthorized in 66ms (ActiveRecord: 3.0ms)

ActiveRecord::RecordInvalid (Validation failed: Coin must exist):

app/controllers/events_controller.rb:23:in `create'

我为我的问题模型设置了相同的方式,因为除了名称之外它们几乎完全相同,并且没有任何问题。我不知道我在这里做错了什么。

控制器:

class EventsController < ApplicationController

  before_action :find_event, only: [:show, :edit, :update, :destroy ]
  before_action :find_coin

  def index  
    @events = Event.where(coin_id: @coin.id).order("created_at DESC")
  end

  def show
  end

  def new
    @event = current_user.events.build
  end

  def create
    @event = current_user.events.build(event_params)
    if @event.save!
      flash[:success] = "Event Saved"
      redirect_to coin_event_path(@coin.id, @event.id)
    else
      flash[:notice] = "Event *NOT* Saved!!!"
      render 'new'
      @event.errors.full_messages
    end
  end
  .
  .
  .
  private

    def find_event
        @event = Event.find(params[:id])
    end

    def find_coin
      @coin = Coin.find(params[:coin_id])
    end

    def event_params
        params.require(:event).permit(:content, :link)
    end
end

模型:

class Event < ApplicationRecord
    belongs_to :user
    belongs_to :coin 
end

硬币模型:

class Coin < ApplicationRecord
    validates :link_name, :currency_name, presence: true
    has_many :questions
    has_many :events
end

如果有人知道我可能做错了什么,或者有任何关于如何弄明白的提示,我真的很感激你的帮助。

2 个答案:

答案 0 :(得分:3)

为需要它并且没有阅读评论的任何人做出答案:)

当你这样做时:

@event = current_user.events.build(event_params)

您实际上创建了一个与用户相关的事件,并且它不再与硬币相关。

在保存前尝试为事件设置硬币:

@event.coin = @coin

或者你可以用另一种方式做 - 在当前硬币上构建事件,然后设置用户:

@event = @coin.events.build(event_params)
@event.user = current_user

这样 - coin_id将自动设置,因为您在event上构建了coin

答案 1 :(得分:0)

我已经解决了相同的问题,在belongs_to方法中添加了“ optional:true”。

belongs_to :user, optional: true

默认情况下,“ belongs_to”需要用户名。

您也可以使用:“必填:false”。

belongs_to :user, required: false

祝你好运。