I am a .NET guy and I try to understand the concept behind Rails and its Active Record stuff.
As I can see in all examples they always assume that your view is a 1:1 copy of your model. In reality frequently that´s not true.
Like a view that holds a customer and contact person(s) that are not related to that customer. User should be able to edit both (customer and contact person(s) in one view e.g.)
In every example I see that they bind the view directly to ONE activerecord object. All the stuff like the model, validation and so on bind to one object that is mapped directly to the database.
Could a Rails guy explain what´s an elegant way to work with Active Record in real life applications in complex model situations? In the first moment I was thinking about DTOs but I could not imagine that this is the way to go with Rails.
Agree with John....
You asked: "Like a view that holds a customer and contact person(s) that are not related to that customer. User should be able to edit both (customer and contact person(s) in one view e.g.)"
Ok, so this is a Customer model that has some employees, right? If not, replace "Employee" with "Person"
/app/model/customer.rb
Class Customer < ActiveRecord::Base
has_many :employees
accepts_nested_attributes_for :employees
end
/app/model/employee.rb
Class Employee < ActiveRecord::Base
belongs_to :customer
end
Then in your view of the customer /app/views/customers/show.html.erb
<%= form_for(@customer) do |f| %>
<%= f.text_field :name %>
.... yada yada ....
<%= f.fields_for(:employees) do |ef| } %>
<%= ef.text_field :first_name%>
<%= ef.text_field :phone %>
<% end %>
<%= f.submit %>
<% end %>
The above has 1 form that lets you save the customer and it's employees. Called Nested Form, and I think does the job of needing "view models".
If you just keep it grouped how real-life is grouped, it goes pretty simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With