Topic: Using javascript to push to ruby array.

I am a newbie to rails.

I posted but some of my code was cut off so here it is in parts.

For clarity though

I have a citations model and authors model  with a author_cites model as a co-joining model

the author_cites model has the foreign keys of author_id and citation_id so I cannot insert into author_cites without first creating a citation

A citation can have many authors though so I need to store the author_id's in a ruby array and iterate over them after the citation is created.
While iterating over them I need to put or create author_cites for each value in the array with the citation id.

Last edited by jjliang (2013-05-03 02:34:52)

Re: Using javascript to push to ruby array.

I have used javascript to display the array and the values from the select on the client side but it will not work on the server side

in the view i have
<%= f.fields_for :author_cites do |a| %>
    <div class="field">
        <div class="span4 offset1">
            <%= a.label :author %>
            <%= collection_select :author_cites, :author_id, @authorlist, :id, :listing_name.to_s, {:prompt => "Last First"},{:class => "span3"} %>
            <br \>
                var myAuthors = new Array();
            <%= button_tag "Add Author",:type => 'button',:class => "btn btn-inverse", :onclick => "addAuthor()"  %> <%authorcitations%>   
<% end %>
<div class="field">
    <div class="span4">
        <%= f.label :current_authors %>
        <div id="current">

Re: Using javascript to push to ruby array.

In the js file i have

addAuthor = function(){
    var myString="";
    var names = new Array();
    var flag = 0;
    value = ($('#author_cites_author_id').val());
    jQuery.each(myAuthors, function index {
        if(myAuthors index ==value){
          flag = 1;
    if(flag == 1){
        alert("Author has already been added");
    else if(value ==""){
        alert("Please select valid author to add");
    else if(value != ""){
        jQuery.each(myAuthors, function index {
                type: "get",
                url: "authors/full_name",
                dataType: 'json',
                data: {id: myAuthors index},
                success: function(data) {
                    myString+= data + "<br />";
                    error: function(){

Re: Using javascript to push to ruby array.

I am thinking of doing this using a helper method. and the html_safe tag. Using javascript to get the value and then push that onto the array.

something like

def authorcitations()
        @aut = content_tag 'script', :type => "text/javascript" do

However, I still don't feel like that would work. I am open to suggestions