Referencing named fixtures (is it possible?)

18 views
Skip to first unread message

strz...@gmail.com

unread,
Sep 23, 2018, 12:20:41 PM9/23/18
to Ruby on Rails: Talk
Hello all,

I cannot seem to find a way how to reference named fixtures in cases where Rails fixtures auto-id magic is not working.

Imagine a model Message with attributes from and to as integers indicating users IDs.

Now the following fixture won't work:

hello_steve:
  to: steve
  from: jana
  text: Hello there!

(Given steve and jana are defined in users.yml. They work for other fixtures defined with standard Rails conventions.)

The thing is I need to reference them here (or their ID).

Thing I tried was to put in place Rails belongs_to:

# user.rb
has_many :sent_messages, class_name: 'Message', foreign_key: 'from'
has_many :received_messages, class_name: 'Message', foreign_key: 'to'

# message.rb
belongs_to :recipient, class_name: 'User', foreign_key: 'to'
belongs_to :author, class_name: 'User', foreign_key: 'from'

Unfortunately Rails won't pick it up and all messages fixtures end up with from and to as '0'.
Note that the association works, just not for fixtures.

Any ideas?

Thank you
Josef

Frederick Cheung

unread,
Sep 23, 2018, 1:02:41 PM9/23/18
to Ruby on Rails: Talk
On Sunday, September 23, 2018 at 5:20:41 PM UTC+1, strz...@gmail.com wrote:
> Hello all,
>
> I cannot seem to find a way how to reference named fixtures in cases where Rails fixtures auto-id magic is not working.
>
> Imagine a model Message with attributes from and to as integers indicating users IDs.
>
> Now the following fixture won't work:
>
> hello_steve:
>   to: steve
>   from: jana
>   text: Hello there!
>

You need to use the association name, not the foreign key, ie (with the associations you have shown):

recipient: steve

Instead of

to: steve.

it also won’t work if you have explicitly assigned an id to steve in the user’s.yml File

Fred
Reply all
Reply to author
Forward
0 new messages