Nikos4Life Nikos4Life - 7 months ago 14
Ruby Question

Test in Rails console model associations?

Hello I do have this two models and I would like to check that my model associations are working the way it should trough rails console.

I am not able to do the association work. The relationship is the following:
One Event has one rule and one rule belongs to one event. It could not be a rule without an event and it could not be a event without a rule.

Any idea how to test this with rails console?

MODEL 1:

class Event < ActiveRecord::Base
has_and_belongs_to_many :users
has_one :rule
has_many :grand_prixes
belongs_to :eventable, polymorphic: :true
end


MODEL 2

class Rule < ActiveRecord::Base
belongs_to :events
end


Rules' Schema:

create_table "rules", force: :cascade do |t|
t.boolean "abs"
t.boolean "tc"
t.boolean "allow_auto_clutch"
t.boolean "allow_sc"
t.boolean "allow_throttle_blip"
t.boolean "dynamic_track"
t.integer "damage_mult"
t.integer "fuel_rate"
t.integer "tyre_wear_rate"
t.integer "quali_percentage"
t.integer "min_valid_laps"
t.integer "event_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

add_index "rules", ["event_id"], name: "index_rules_on_event_id"


Events' Schema:

create_table "events", force: :cascade do |t|
t.string "event_type"
t.string "name", null: false
t.datetime "starting_date"
t.datetime "ending_date"
t.integer "eventable_id"
t.string "eventable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

add_index "events", ["eventable_type", "eventable_id"], name: "index_events_on_eventable_type_and_eventable_id"


Thanks in advance.

Answer

I think your belongs_to :events should be singular to follow the rails convention :

class Rule < ActiveRecord::Base
  belongs_to :event
end

The conventional name of a relation is always singular for belongs_to and has_one, and always plural for has_many.

Related documentation : http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference

EDIT : There much left to say

You wrote :

ev = Event.create(:name "test1").save
rule = Rule.create.save
  • create is already a new followed by a save. No need to save afterwards.
  • the syntax key: value is something very common in ruby, and should be well understood : you're actually writing a hash, equivalent to {:key => value}, but the syntax allows you to write key: value ONLY IF your key is a Symbol.
  • the columns eventable_type and eventable_id should be in the table rules, who is hosting the polymorphic relation with eventable things. Event should not have these columns, and event_id should not exist at all in rules.

Here's an example of what you can write in your console to create an Event and a Rule :

ev = Event.create(name: "test1")
rule = Rule.create(abs: true, event: ev)