Using Struct with Rails

I recently met this messaging tutorial and was intrigued using Struct.new. With some help from google and https://stackoverflow.com/a/166269/2128/ I have learned a little more about using Struct in Ruby, but I would like to know a little more about using it in Rails. The textbook has a model of the folder in which the messages received by the user are stored:

class Folder < ActiveRecord::Base acts_as_tree belongs_to :user has_many :messages, :class_name => "MessageCopy" end 

An inbox is created when a new user is created:

 class User < ActiveRecord::Base has_many :sent_messages, :class_name => "Message", :foreign_key => "author_id" has_many :received_messages, :class_name => "MessageCopy", :foreign_key => "recipient_id" has_many :folders before_create :build_inbox def inbox folders.find_by_name("Inbox") end def build_inbox folders.build(:name => "Inbox") end end 

However, the 'trash' folder is created on the fly using Struct.new:

 class MailboxController < ApplicationController def index @folder = current_user.inbox show render :action => "show" end def show @folder ||= current_user.folders.find(params[:id]) @messages = @folder.messages.not_deleted end def trash @folder = Struct.new(:name, :user_id).new("Trash", current_user.id) @messages = current_user.received_messages.deleted render :action => "show" end end 

What are the benefits of using Struct with Rails? Why is it used in this tutorial to create the Trash folder and not the Inbox (which can also be created when the user is created)? Thanks for the help, I didn't learn too much about when Struct can / should be used with Rails!

+4
source share
1 answer

There is no use, only some considerations behind her:

  • User can create own folders.
  • The recycle bin in this example is a virtual folder containing all messages marked as deleted.

In order for your views to work in both cases, the author decided to create a fake folder object (one that does not have all active entries, so it cannot be saved, etc.). Then he reveals his views.

 <%= @folder.name %> 

will work whether it is a fake folder or a real folder.

+3
source

All Articles