简体   繁体   中英

Declare Array Variable To Use In A Ruby On Rails View

I am using Ruby 1.9.3 and Rails 3.2.6. I want to create a page where users can invite friends to sign up. The page would contain a number of fields where a user can enter email addresses. I would like these stored in an array. Basically each field on the page would be an element in the array. My hope is to loop through the array elements, verify each email address entered, update a temp email field on my table then launch an ActionMailer to send the invite email.

I would like this array initialized each time the user goes to the invite page. From what I have read in the book Programming Ruby 1.9 I should be able to declare an array like this somewhere.

friend_email = Array.new

I need the variable available long enough to access it in my controller when I verify the data entered in my view. From my limited understanding of variables they generally are not available outside of where they are declared aka initialized. This makes it interesting when trying to send entered information to a mailer. I have used temp fields on my model to simplify things.

If there is a better way to do this I would appreciate the information. I will also continue doing research. I have seen only the one I list below where an array is populated by an existing table then displayed in a view. I want to populate the array from the view.

Render an array in a view in ruby on rails

Any help would be appreciated.

Well, i believe a good approach to this problem could be the use of a single text_field that the user would input emails separated by commas/colons/semi-colons/whatever, and when submited, the controller would separate these emails using the split method and some regex, then validate each one of those. If a validations passes you have on your hand an array of emails.
I don't think you really need an array to do this.

I don't see how your Active Record (AR) model is at all involved if all you want to do is show/process a list of email addresses. If they don't need to be in the dbms and aren't involved with an AR model, then don't involve an AR model.

To answer the title of your q: "Declare Array Variable To Use In A Ruby On Rails View" --

A: declare the array as an instance variable in the controller. (instance variables start with an @) All instance variables declared in the controller are automatically available in the view.

def show_emails
  @emails = []
return  # the view "show_emails" will be used

def process_emails
  @emails = params['emails'] || []

  ...
     # check the emails. If there's a bad one, you can 
     #   re-render the show_emails view with an error msg
     # or send out the emails and then show a confirmation page
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM