#user.rb
class User < ApplicationRecord
has_many :user_activities
has_many :activities, through: :user_activities
end
#activity.rb
class Activity < ApplicationRecord
has_many :user_activities
has_many :users, through: :user_activities
end
#user_activity.rb
class UserActivity < ApplicationRecord
belongs_to :user
belongs_to :activity
end
Я скопировал ваши модели в небольшое приложение и попробовал выполнить операции с консоли Rails. Это должно дать вам лучшее понимание
Loading development environment (Rails 5.2.2)
2.4.1 :002 > Activity.last
(0.3ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
Activity Load (0.2ms) SELECT `activities`.* FROM `activities` ORDER BY `activities`.`id` DESC LIMIT 1
=> nil
2.4.1 :004 > obj = Activity.new(name: "Cricket", activity_type: "Sports")
=> #<Activity id: nil, name: "Cricket", created_at: nil, updated_at: nil, activity_type: "Sports">
2.4.1 :005 > obj.save
(0.2ms) BEGIN
Activity Create (0.4ms) INSERT INTO `activities` (`name`, `created_at`, `updated_at`, `activity_type`) VALUES ('Cricket', '2019-01-16 05:20:10', '2019-01-16 05:20:10', 'Sports')
(6.4ms) COMMIT
=> true
2.4.1 :007 > obj1 = User.new(name: "user1",city: "city1")
=> #<User id: nil, name: "user1", role_id: nil, created_at: nil, updated_at: nil, city: "city1">
2.4.1 :008 > obj1.save
(0.2ms) BEGIN
User Create (0.4ms) INSERT INTO `users` (`name`, `created_at`, `updated_at`, `city`) VALUES ('user1', '2019-01-16 05:20:59', '2019-01-16 05:20:59', 'city1')
(5.9ms) COMMIT
=> true
Итак, я создал некоторые фоновые данные перед следующими операциями,
2.4.1 :001 > user = User.last
(0.3ms) SET NAMES utf8, @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'), @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
User Load (0.3ms) SELECT `users`.* FROM `users` ORDER BY `users`.`id` DESC LIMIT 1
=> #<User id: 1, name: "user1", role_id: nil, created_at: "2019-01-16 05:20:59", updated_at: "2019-01-16 05:20:59", city: "city1">
2.4.1 :002 > obj1 = user.user_activities.build
=> #<UserActivity id: nil, user_id: "1", activity_id: nil, created_at: nil, updated_at: nil>
2.4.1 :003 > obj1.save
(0.3ms) BEGIN
(0.2ms) ROLLBACK
=> false
2.4.1 :004 > obj1.errors.full_messages
=> ["Activity must exist"]
2.4.1 :005 > obj1 = user.user_activities.build(activity_id: Activity.last.id)
Activity Load (0.3ms) SELECT `activities`.* FROM `activities` ORDER BY `activities`.`id` DESC LIMIT 1
=> #<UserActivity id: nil, user_id: "1", activity_id: "1", created_at: nil, updated_at: nil>
2.4.1 :006 > obj1.save
(0.2ms) BEGIN
Activity Load (0.3ms) SELECT `activities`.* FROM `activities` WHERE `activities`.`id` = 1 LIMIT 1
UserActivity Create (0.2ms) INSERT INTO `user_activities` (`user_id`, `activity_id`, `created_at`, `updated_at`) VALUES ('1', '1', '2019-01-16 05:23:32', '2019-01-16 05:23:32')
(5.6ms) COMMIT
=> true
["Активность должна существовать"], найдите эту ошибку в консоли, и причина в том, что код_действия не был передан объекту user_activity. Теперь обновите ваш код в контроллере
activity_id = #fetch this value from params as it comes
@user_activity = current_user.user_activities.new(activity_id: activity_id)
Я вижу, что у вас есть метод user_activity_params с несколькими атрибутами, как только приведенный выше код работает, проверьте его с новой строкой, если требуется.
@user_activity = current_user.user_activities.new(user_activity_params)