I’m writing a rails calendar app for planning a social media editorial calendar.
My relationships are: User has_many Calendars, Calendar has_many Users
I’m trying to implement a calendar admin where the calendar also belongs to admin. The admin is whoever created the calendar.
I have searched all over here and found different options that were just has_many and belongs_to relationships, not adding the belongs_to to the join relationship.
I have tried doing:
class Calendar < ApplicationRecord
has_many :user_calendars
has_many :users, :through => :user_calendars
has_many :calendar_posts
has_many :posts, :through => :calendar_posts
belongs_to :admin, :class_name => :User
def add_calendar
Calendar.new(admin: self)
end
class CalendarsController < ApplicationController
def create
@calendar = Calendar.new(calendar_params)
current_user.add_calendar
if @calendar.save
redirect to @calendar
else
render :new
end
end
private
def calendar_params
params.require(:calendar).permit(:name, :user_id)
end
This just rendered new and the only thing I got from the server log was rollback. I typed in errors and they were empty.
I’ve also tried to do something like another post I saw on here where I removed the add_calendar method from the user model and that line of code in the calendar controller and instead had a private method in the calendar controller under private:
def set_admin
@calendar.admin.id = current_user.id
end
And at the top of calendar controller have:
before_action :set_admin, only: :create
This gave me the stack error Syntax warning
I had also tried adding a migration for adding admin column to Calendar table with integer as the type?
I do have Devise set up for user registration but was trying to Ashlie using it for this functionality if possible.
I see that you create a new entity calendar in the user not related to the current one on not save it. Please try:
And yes you need to add a migration where you add admin_id to the calendar