On Sunday, September 23, 2018 at 5:20:41 PM UTC+1, strzibny@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
> (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
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/adaf5c7c-14fe-4d32-9a23-1fcbf9591663%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment