1错误禁止保存此频道:

时间:2017-12-16 08:30:37

标签: ruby-on-rails ruby

我有一个用户和帖子的rails应用程序,我添加了另一个叫做频道的sacffold,现在关系就像用户可以创建帖子和频道,频道属于用户,帖子属于用户和频道,到将用户ID添加到已创建迁移的频道,一切看起来不错,但我在创建频道时遇到此错误。 (Here is a screenshot of the exact error)

这就是命令行上的内容:

Started POST "/channels" for 127.0.0.1 at 2017-12-16 13:30:32 +0530
Processing by ChannelsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"IJvvEe+TR6buacH5UwtiLSJglMkq7a+Q4x7VOTqALcGka4j6tG7lPi/7kYnCQ/nzmO7PNe2eSan3sBz9NqKV2g==", "channel"=>{"name"=>"dhfkdhfk", "description"=>"jdfjdfh", "tagline"=>"jdfjdfhj", "category"=>"jdfjdf", "avatar"=>""}, "commit"=>"Create Channel"}
  User Load (2.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (2.6ms)  BEGIN
   (1.8ms)  ROLLBACK
  Rendered channels/_form.html.erb (11.5ms)
  Rendered channels/new.html.erb within layouts/application (13.3ms)
  Rendered layouts/_avatar_dropdown.html.erb (7.4ms)
  Rendered layouts/_header.html.erb (12.6ms)
  Rendered layouts/_alert_messages.html.erb (0.5ms)
Completed 200 OK in 367ms (Views: 345.3ms | ActiveRecord: 6.7ms)

Add_user_id_to_channel.rb

class AddUserIdToChannels < ActiveRecord::Migration
  def change
    add_reference :channels, :user, index: true, foreign_key: true
  end
end

channel.rb

class Channel < ActiveRecord::Base
    validates :name, :description, :user_id, presence: true
    belongs_to :user
    has_many :posts, dependent: :destroy
end

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :omniauthable, :omniauth_providers => [:facebook, :twitter, :google_oauth2]

         act_as_mentionee

  validates :username, presence: true
  validate :avatar_image_size

  has_many :posts, dependent: :destroy
  has_many :channels, dependent: :destroy
  has_many :responses, dependent: :destroy
  has_many :likes, dependent: :destroy

  after_destroy :clear_notifications
  after_commit :send_welcome_email, on: [:create]


  mount_uploader :avatar, AvatarUploader

  include UserFollowing
  include TagFollowing
  include SearchableUser
  include OmniauthableUser


  private

    # Validates the size on an uploaded image.
    def avatar_image_size
      if avatar.size > 5.megabytes
        errors.add(:avatar, "should be less than 5MB")
      end
    end

    # Returns a string of the objects class name downcased.
    def downcased_class_name(obj)
      obj.class.to_s.downcase
    end

    # Clears notifications where deleted user is the actor.
    def clear_notifications
      Notification.where(actor_id: self.id).destroy_all
    end

    def send_welcome_email
      WelcomeEmailJob.perform_later(self.id)
    end
end

user_controller

class UsersController < ApplicationController
  before_action :authenticate_user!, only: [:edit, :update]
  before_action :authorize_user, only: [:edit, :update]
  before_action :set_user, only: [:show, :edit, :update]

  def show
    @followers_count = @user.followers.count
    @following_count = @user.following.count
    @latest_posts = @user.posts.latest(3).published
    @recommended_posts = @user.liked_posts.latest(4).published.includes(:user)
  end

  def update
    if @user.update(user_params)
      redirect_to @user
    else
      render :edit, alert: "Could not update, Please try again"
    end
  end

  private

    def set_user
      @user = User.find(params[:id])
    end

    def user_params
      params.require(:user).permit(:description, :avatar, :location, :username)
    end

    def authorize_user
      unless current_user.slug == params[:id]
        redirect_to root_url
      end
    end
end

channel_controller

class ChannelsController < ApplicationController
  before_action :set_channel, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:show]
  before_action :authorize_user, only: [:edit, :update, :destroy]

  # GET /channels
  # GET /channels.json
  def index
    @channels = Channel.all
  end

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

  # GET /channels/new
  def new
    @channel = Channel.new
    @channel = current_user.channels.build
    @user = current_user
  end

  # GET /channels/1/edit
  def edit
  end

  # POST /channels
  # POST /channels.json
  def create
    @channel = current_user.channels.build(channel_params)
    @channel = Channel.new(channel_params)
    @user = current_user


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

  # PATCH/PUT /channels/1
  # PATCH/PUT /channels/1.json
  def update
    respond_to do |format|
      if @channel.update(channel_params)
        format.html { redirect_to @channel, notice: 'Channel was successfully updated.' }
        format.json { render :show, status: :ok, location: @channel }
      else
        format.html { render :edit }
        format.json { render json: @channel.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /channels/1
  # DELETE /channels/1.json
  def destroy
    @channel.destroy
    respond_to do |format|
      format.html { redirect_to channels_url, notice: 'Channel was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def channel_params
      params.require(:channel).permit(:name, :description, :tagline, :category, :avatar, :user_id)
    end

    def authorize_user
      begin
        @channel = current_user.channels.find(params[:id])
      rescue
        redirect_to root_url
      end
    end
end

2 个答案:

答案 0 :(得分:0)

在频道模型中,您创建了&#39; user_id&#39;通过添加存在强制提交:true

validates :name, :description, :user_id, presence: true

因此您必须在参数中传递user_id。你可以通过在视图中添加hidden_​​filed来实现这一点

 <%= f.hidden_field :user_id, value: @user %>

或者如果您不需要&#39; user_id&#39;删除表单验证如下:

validates :name, :description, presence: true

答案 1 :(得分:0)

更改

is

@channel = current_user.channels.build(channel_params)
@channel = Channel.new(channel_params)