ruby-on-railsruby-on-rails-4fabrication-gem

Rails fabricator - how to get value from association field?


Let's say that I have a model User which has many Notes. Each note has the field user_name. I would like my notes Fabricator to look something like this:

Fabricator(:note, class_name: Note) do
  user
  content Faker::Lorem.paragraph(1)
  user_name user.full_name
end

What I'm trying to do is set the user_name with the value from the full_name method from the User that already exists. But I'm getting the following error:

undefined method `full_name' for #<Fabrication::Schematic::Attribute:0x0000000a279c50>

Any help would be appreciated.


Solution

  • Found out eventually in the documentation that there is an attributes hash I can use:

    Fabricator(:note, class_name: Note) do
      user
      content Faker::Lorem.paragraph(1)
      user_name { |attrs| attrs[:user].full_name }
    end