I have a simple rails app that functions as a cms for a digital signage application.
In this app, there will be a pool of predefined styles that I want to offer to all users.
Every style includes a background picture, some css and a video.
My goal is to get a setup where I can prepare different styles, add them using rails admin and every user should have a menu where he can choose one of the styles as active_style for his account.
Sounds easy, but the point where I'm stuck is the associations between the User and the Style models.
I tried different things for several hours (has_many: / has_many_though / has_and_belongs_to_many), but I cannot get to the point where each user can pick one of the style objects and make it their active_style, and allow just one active_style at a time.
I just wonder what is the best way to do this and would be very happy if someone could help out.
I'm relatively new to rails programming, please excuse if this seems stupid.
I know it sounds unintuitive, but I think the association you want in this case is "belongs_to". I say it's unintuitive because it sounds strange saying "a user belongs to an active style", but "has_one" would not allow a single style to be the active style for multiple users.
The following code assumes you have an "active_style_id" integer column on your Users table that will store the foreign key:
User < ActiveRecord::Base
belongs_to :active_style, class_name: 'Style'
end
This will then let you do things like:
style = Style.find(...)
user = User.create(active_style: style)
user.active_style # => style