Florin Lei
Florin Lei

Reputation: 519

Ruby on Rails association objects

I'm new on Ruby on Rails, so please sorry if the question sounds stupid or is a duplicate question, but I have searched for an answer but without success.

I have the following example

User class

class User < ApplicationRecord
    has_many :preference, dependent: :destroy
end

Preference class

class Preference < ApplicationRecord
    belongs_to :user
end

So what I'm trying is to create a new Preference with following code

preference = PreferenceService.validate_start_and_end_date(Preference.new(preference_params))

Then I would like to save like following

current_user.preference.save(preference)

I tried multiple approaches but with no success. I'm using ruby 2.5.3p105 with Rails 5.2.1.1

Thank you

Upvotes: 0

Views: 47

Answers (1)

widjajayd
widjajayd

Reputation: 6253

here some of the idea with your code above

since you use has_many, you have to follow rails convention with preferences (plural form)

class User < ApplicationRecord
  has_many :preferences, dependent: :destroy
end

Preference class

class Preference < ApplicationRecord
    belongs_to :user
    validate :valid_start_and_end_date?

private

  def valid_start_and_end_date?
    # here you do rule validation for start_date and end_date field
    # for example you check end_date value must greater than or equal start_date
    start_date <= end_date
  end
end

create preference with this steps

since each preference must have a user then first you must 
@preference = Preference.new(preference_params)
@user = User.find_by_username("johndoe")
@preference.user = @user
@preference.save

Upvotes: 2

Related Questions