Reputation: 4089
I have been having issues with the way I want to write my if else logics in the new action of my controller. For instance a user has two different fildes in the user table, let us say premium_user and gold_user. How will I write an if else statement that says if a user is a premium user he can upload 3 books and if the user is a gold user he can upload unlimited books and of he is just a user without gold or premium he can only upload 2 books in the new action of my controller. Thank you
Upvotes: 1
Views: 166
Reputation: 8884
well, you can choose to upload your books with a user form (using nested attributes), or directly with book form. you can put validation to the user.
class User
has_many :books
validates :books, :length => { if: Proc.new { |r| r.gold? }, allow_nil: true, maximum: 3, too_long: 'gold users can only upload 3 books' }
validates :books, :length => { if: Proc.new { |r| r.standard? }, allow_nil: true, maximum: 3, too_long: 'gold users can only upload 3 books' }
end
class Book
belongs_to :user
validates :user, :presence => true, associated: true
end
Even if you submit it via books, make sure you create a new books with user.books.build
, in order for the validation to behave correctly.
Note that your controller new or create action will be the same, no need to fork on user type for validation.
Maybe you want to put a note in your books/new view or disable the form if users reach maximum allowable upload.
hope this helps
Upvotes: 1