1错误禁止保存此频道:

问题描述 投票:0回答:2

我有一个用户和帖子的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
ruby-on-rails ruby
2个回答
0
投票

在频道模型中,您通过添加在线状态强制提交“user_id”:true

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

所以你必须在参数中传递user_id。你可以通过在视图中添加hidden_​​filed来做到这一点

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

或者,如果您不需要'user_id',请删除表单验证,如下所示:

validates :name, :description, presence: true

0
投票

更改

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

@channel = current_user.channels.build(channel_params)
© www.soinside.com 2019 - 2024. All rights reserved.