Rails创建新表后出错

时间:2018-05-28 09:31:54

标签: ruby-on-rails database model has-many-through has-many

(抱歉我的英文) 您好,我为我的错误创建了一个新帖子,以便更清楚地解释发生了什么 我添加了一个表“user-activities”,它允许我知道用户是否看到了某个活动 这是我的数据库的表示

DB 我的问题是我不能再创作一篇文章了 显然问题出现在保存中:

日志:

Started POST "/activities" for 127.0.0.1 at 2018-05-24 17:21:49 +0200
Processing by ActivitiesController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Cq573getfK9HBo4U9xiftsdtmScb08A28AWCcwTq2+Csn7u2hmylpjMdaB5qtJ6ZfWoHV/TZ+zF0xtgPCCp69Q==", "activity"=>{"title"=>"Activity 1 ", "content"=>"<p>dzdzqdqzdqz</p>", "group_id"=>"2"}, "commit"=>"Créer l'activité"}
  User Load (4.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ /home/benjamin/.rbenv/versions/2.5.0/lib/ruby/gems/2.5.0/gems/activerecord-5.2.0.rc1/lib/active_record/log_subscriber.rb:98
   (0.2ms)  BEGIN
  ↳ app/controllers/activities_controller.rb:9
  Group Load (2.3ms)  SELECT  "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ app/controllers/activities_controller.rb:9
   (0.2ms)  ROLLBACK
  ↳ app/controllers/activities_controller.rb:9
Redirected to http://localhost:3000/
Completed 200 OK in 19ms (ActiveRecord: 7.4ms)

#activities_controller.rb:9 =>     if @activity.save

控制器:

  def create
    @activity = Activity.new(activity_params)
    @activity.user = current_user
    if @activity.save
      flash[:notice] = "Votre activité a été créée !"
      redirect_to root_path
    else
      flash[:alert] = "Erreur lors la création"
      redirect_to root_path
    end
  end

当我添加新表时,控制器没有改变,并且创建新活动的表单不包含错误(组ID /用户IS /内容/标题/日期等等...有效)

我的模特已经改变了:

BEFORE

活动模型:

class Activity < ApplicationRecord
  belongs_to :user
  belongs_to :group
  validates :content, presence: true
end

用户模型:

class User < ApplicationRecord
  rolify
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :user_groups
  has_many :activities
end

之后:

活动模型:

class Activity < ApplicationRecord
  has_many :user_activities, dependent: :destroy
  has_many :users, through: :user_activities
  belongs_to :user, class_name: 'User'
  belongs_to :group
  validates :content, presence: true
end

用户活动模型:

class UserActivity < ApplicationRecord
  belongs_to :activity
  belongs_to :user    
end

用户模型:

class User < ApplicationRecord
  rolify
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :user_groups
  has_many :user_activities
  has_many :activities, through: :user_activities

end

谢谢:)

1 个答案:

答案 0 :(得分:1)

在开发过程中,必须将@activity.save替换为@activity.save!,并获取有关错误的详细信息的异常。