Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Physical posted:

Ok so this is kind of a rudimentry question but I am having a hard time dissecting it to do a fruitful google search.

I have a HighLazyChart object that I am trying to get the data array out of. Here is what I got so far.

code:
# ...
The code that generates that output is the following too lines
<%= @blah.inspect %>
<%= @blah.data.inspect %>

Now, I want access to the :data array in the @blah.data.inpsect line, the one with the 3,3,3,3,3 values in it. But @blah.data.data doesn't work and neither does @blah.data[:data] How the hell do I get access to that and also how do I do this in the future? How do I understand what the inspect dump is displaying and how to access the object data?

Um yeah it looks like LazyHighChart.data is an array object, as connoted by the [] operator wrapping it. So in this case you could try @data[0][:data] or even @data.first[:data].

Unless @data is going to point to a collection of hashes you might want to think about refactoring. But there's not enough code to tell.

Also use carriage returns when posting code please.

A MIRACLE fucked around with this message at 15:35 on Mar 20, 2012

Adbot
ADBOT LOVES YOU

Physical
Sep 26, 2007

by T. Finninho
Thanks. Shortly after submitting my question I figured out the correct answer which also what you answered with:
<%= @blah.data[0][:data] %>

I had to stare at the dump to understand what was going on, I noticed the curly brackets and realized "oh duh, this is an array inside of here, I have to access it using multi-dimensional array syntax"

This always seems to happen to me, I submit a question online or via email and figure it out shortly after before I get a reply back. It's like typing the question out helps me formalize what I'm thinking and helps me see it from someone else's perspective.

Thanks again!

Physical fucked around with this message at 16:03 on Mar 20, 2012

prom candy
Dec 16, 2005

Only I may dance
Just to clarify, what you've got there is a Hash inside of an Array.

@blah.data.class would return Array
@blah.data[0].class would return Hash

For some reason coming to Ruby from PHP I found distinguishing between Arrays and Hashes took me a long time, probably because in PHP an array is kind of both.

plasticbugs
Dec 13, 2006

Special Batman and Robin
My site lets users create a bunch of messages.

The users#show page lists all of the user's messages BUT also includes a form at the bottom for creating a new message.

So, my User Show action looks like this:

code:
def show
    @user = User.find(params[:id])
    @messages = @user.messages
    @message = Message.new
end
The problem is, if the user tries to create an invalid Message, the page re-renders and the invalid message gets tacked onto the user's list of messages just by virtue of the fact that the new message now has the User's ID in its user_id column - even though the message is invalid.

Is there a better way to avoid this problem than doing something like what I typed below in my view? This feels hacky:

@messages.each do |message|

if message.valid?
<%= message %>
end
end

prom candy
Dec 16, 2005

Only I may dance
What does your create action look like? Are you creating the message in a separate messages controller? This pretty much all has to do with when you're setting the value of @messages.

plasticbugs
Dec 13, 2006

Special Batman and Robin

prom candy posted:

What does your create action look like? Are you creating the message in a separate messages controller? This pretty much all has to do with when you're setting the value of @messages.

Here's my create action in my Messages controller. It's a little messy because Messages can be created without an account by design, so I have to cover a few cases.

The case described above is where the User is signed in, and the message created isn't valid.

code:
 def create
    
    if signed_in?
      @user = current_user
      @message = @user.messages.build(params[:message])
    else
      @message = Message.new(params[:message])
    end
        
    if @message.save
      flash[:notice] = 'Your page was created!'
      redirect_to :action => "show", :pickUpCode => @message.pickUpCode

    elsif @message.save && signed_in?
      render :action => 'users/show', :messages => current_user.messages

    elsif !@message.valid? && signed_in?
      render :template => 'users/show'
    
    else

      redirect_to root_url
    end
  end

prom candy
Dec 16, 2005

Only I may dance
So we're talking about the case where "!@message.valid? && signed_in?" right?

Maybe my memory is wrong but I didn't think render :template ran the controller action. How is @messages getting set for the view? Or are you just calling @user.messages directly in the view?

plasticbugs
Dec 13, 2006

Special Batman and Robin

prom candy posted:

So we're talking about the case where "!@message.valid? && signed_in?" right?

Maybe my memory is wrong but I didn't think render :template ran the controller action. How is @messages getting set for the view? Or are you just calling @user.messages directly in the view?
Yep, we're talking about "!@message.valid? && signed_in?". Thanks for your help.

Originally, I had a redirect action in there, but then my flash[:error] wasn't persisting. Either way, with either redirect or render :template, the extra invalid message was displaying in the user's list of messages.

I didn't do a copy paste. I retyped my code into my post, I forgot that line. Here's what my create action actually is:
code:
 def create
    
    if signed_in?
      @user = current_user
      @messages = @user.messages
      @message = @user.messages.build(params[:message])
    else
      @message = Message.new(params[:message])
    end
        
    if @message.save
      flash[:notice] = 'Your page was created!'
      redirect_to :action => "show", :pickUpCode => @message.pickUpCode

    elsif @message.save && signed_in?
      render :action => 'users/show', :messages => current_user.messages

    elsif !@message.valid? && signed_in?
      render :template => 'users/show'
    
    else

      redirect_to root_url
    end
  end

prom candy
Dec 16, 2005

Only I may dance
Is your view code references @messages or @user.messages? Actually can you paste your whole view (or at least the relevant parts)?

Edit: use gist.github.com to save the table-breakage

prom candy fucked around with this message at 21:05 on Mar 21, 2012

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

plasticbugs posted:

Here's my create action in my Messages controller. It's a little messy because Messages can be created without an account by design, so I have to cover a few cases.

The case described above is where the User is signed in, and the message created isn't valid.

code:
 def create
    
    if signed_in?
      @user = current_user
      @message = @user.messages.build(params[:message])
    else
      @message = Message.new(params[:message])
    end
        
    if @message.save
      flash[:notice] = 'Your page was created!'
      redirect_to :action => "show", :pickUpCode => @message.pickUpCode

    elsif @message.save && signed_in?
      render :action => 'users/show', :messages => current_user.messages

    elsif !@message.valid? && signed_in?
      render :template => 'users/show'
    
    else

      redirect_to root_url
    end
  end

A little refactoring to help isolate and remove some precedence bugs:

code:
  def create
    @message = Message.new params_for_message
        
    return message_create_failed unless @message.save

    return message_create_succeeded
  end

  def params_for_message
    params[:message].merge(user: current_user)
  end

  def message_create_succeeded
    if signed_in?
      return render action: 'users/show', messages: current_user.messages
    end

    return redirect_to action: 'show', pickUpCode: @message.pickUpCode
  end

  def message_create_failed
    if signed_in?
      return render template: 'users/show'
    end

    return redirect_to root_url
  end

plasticbugs
Dec 13, 2006

Special Batman and Robin

BonzoESC posted:

A little refactoring to help isolate and remove some precedence bugs:


I did refactor as suggested, thanks. It's much cleaner, but I'm still having the same problem. EDIT: The problem is gone, though I had to add the following to my create action:

@user = current_user
@messages = @user.messages

Just in case you were curious, here is a link to my User Show view - showing the relevant code:
https://gist.github.com/2154099

Though it seems the problem did indeed lie somewhere in not properly ordering all my ridiculous if else statements. Me code pretty one day. Thanks for your help Bonzo and prom candy!

Edit 2: Also, I should probably start weaning myself off of hash rockets.

plasticbugs fucked around with this message at 00:35 on Mar 22, 2012

ShadowHawk
Jun 25, 2000

CERTIFIED PRE OWNED TESLA OWNER
If I have a ruby script open a file with an exclusive lock, and then have several other concurrent scripts try and do the same such that they're all waiting on it, which one gets it first?

Random?
First in first out?
Whichever has lowest niceness?

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

ShadowHawk posted:

If I have a ruby script open a file with an exclusive lock, and then have several other concurrent scripts try and do the same such that they're all waiting on it, which one gets it first?

Random?
First in first out?
Whichever has lowest niceness?

That's an OS kernel question; read the source or run an experiment perhaps?

Physical
Sep 26, 2007

by T. Finninho
edit: sigh nevermind I fixed it, it was my error.

re-edit: actually It wasn't my error. Something is still bugging me

accounts.each do |u|
account = Account.create(:name => u[:name], :domain => 'example', :admin_attributes => u, :plan => SubscriptionPlan.last)
account_id = account if u[:name].eql?('example')
end

This doesn't work, and it looks like its the :domain field, but if I switch it to grabbing it out of a hash it magically works. WTF?

account = Account.create(:name => u[:name], :domain => u[:name], :admin_attributes => u, :plan => SubscriptionPlan.last)

Physical fucked around with this message at 18:27 on Mar 23, 2012

ShadowHawk
Jun 25, 2000

CERTIFIED PRE OWNED TESLA OWNER

BonzoESC posted:

That's an OS kernel question; read the source or run an experiment perhaps?
In a way that actually answers it. I had assumed (wrongly I suppose) that the ruby interpreter which is handling the locks was also handling which process to unlock once they started hanging together.

Physical
Sep 26, 2007

by T. Finninho
What would it take to generate a valid helper like this

new_department_activity_path(@department)

If you had two seperate MVCs for both Departments and Controllers?

They are two symbiotic classes and work together semantically but I don't see any occurances of a controller or a defintion for department_activity, or departmentactivity.

Does it come from nested routing? That seems like the only way I can see how a programmer could hook this up from this source code I have.

routes.rb

resources :departments do
resources :activities
end

Physical fucked around with this message at 10:09 on Mar 24, 2012

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Physical posted:

What would it take to generate a valid helper like this

new_department_activity_path(@department)

If you had two seperate MVCs for both Departments and Controllers?

They are two symbiotic classes and work together semantically but I don't see any occurances of a controller or a defintion for department_activity, or departmentactivity.

Does it come from nested routing? That seems like the only way I can see how a programmer could hook this up from this source code I have.

routes.rb

resources :departments do
resources :activities
end

If you run rake routes you can see all the routes and helpers your routes file generates. It'll hopefully help you answer this one.

Physical
Sep 26, 2007

by T. Finninho

BonzoESC posted:

If you run rake routes you can see all the routes and helpers your routes file generates. It'll hopefully help you answer this one.
Wow thats great thanks.

I have a form that contains multiple instances of the same form, so I need to add a series ID to each of the inputs to help differentiate them. How can I do that using this kind of structure?

code:
<%= form_for(external_contact) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
<% end %>


The input will have a name tag equal to "external_contact[name]" but I want to it be "external_contact[id][name]" without changing the above code to this"

code:
<%= form_for(external_contact) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= text_field_tag "external_contact[#{id}[name]" %>
  </div>
<% end %>


Or maybe theres another method that will save me from having to change all these fields but will allow me to have multiple instances of the same form with the same field names on a single index page.

enki42
Jun 11, 2001
#ATMLIVESMATTER

Put this Nazi-lover on ignore immediately!
Are all of these external contacts children of some other parent relationship? If so, you could base your form around the parent relationship and use accepts_nested_attributes_for on the parent model so you can pass a bunch of external contacts into the parent.

Physical
Sep 26, 2007

by T. Finninho

enki42 posted:

Are all of these external contacts children of some other parent relationship? If so, you could base your form around the parent relationship and use accepts_nested_attributes_for on the parent model so you can pass a bunch of external contacts into the parent.

Yes there is a parent relationship. The parent type is called document_section. What more do I have to do to get the relationship working properly?

So far, it's just external_contacts belongs_to :document_section and a document_section has many external_contacts. Is that enough? The examples for all these helpers are like non existant because I read about accepts_nested_attributes_for and while it sounded like it might be helpful I didn't really get a grasp on how to use it from the ruby api docs.

prom candy
Dec 16, 2005

Only I may dance
You're going in the right direction, accepts_nested_attributes_for is a good way to build little sub-forms for your child elements.

Try this: http://railscasts.com/episodes/196-nested-model-form-part-1

Physical
Sep 26, 2007

by T. Finninho
Today I learned how important it can be to put :remote => true in your forms and links :doh:

prom candy
Dec 16, 2005

Only I may dance
Do people still use that?

Pardot
Jul 25, 2001




prom candy posted:

Do people still use that?

Wasn't that for RJS?

prom candy
Dec 16, 2005

Only I may dance

Pardot posted:

Wasn't that for RJS?

Something like that.

Physical, why are you using :remote => true in your links?

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Pardot posted:

Wasn't that for RJS?

I think now it just uses the rails-ujs driver for Jquery.

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

Something like that.

Physical, why are you using :remote => true in your links?
Why wouldn't I? I'm using it for Ajax/jquery calls that have to send data to the server.

Basically, it allows you to take something that is in show form, click edit and it replaces the show with an edit form, and then save and it goes back to the show form and updates the data on the client and db.

prom candy
Dec 16, 2005

Only I may dance
Ah okay, it's the thing that writes your jQuery Ajax calls for you. I've been doing it by hand for a long time because it used to write inline JavaScript. I think it's probably better now.

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

Ah okay, it's the thing that writes your jQuery Ajax calls for you. I've been doing it by hand for a long time because it used to write inline JavaScript. I think it's probably better now.
Yea so far its pretty sweet. I don't even have to learn AJAX. In fact, I still don't know AJAX. I never got into web dev far enough to do AJAX stuff, it was always redirects and the old methodology until now and RoR does it all for me. Its great.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Nowadays it pretty much just adds the data-remote="true" attribute to your links, which the rails-ujs driver knows how to pick up.

prom candy
Dec 16, 2005

Only I may dance
Solid. How do you tell it which area to update? I still have memories of multi-line link_to_remote calls in my views back in Rails 0.x. Not pretty.

Physical
Sep 26, 2007

by T. Finninho
Write it as a controller. And then render a document.js.erb thing that does the code. So if I want to target a specfific div I put this in the .js.erb file that gets called after the particular controller function is called:

$('#divid').html("<%j render "dir/form %>")

I can go into more detail if you'd like.

Physical
Sep 26, 2007

by T. Finninho
Is there something that I don't know that prevents me from assigning a value to a key in a hash.each loop?

code:
     #ok so we have our list of locations, now find the staff resources that have this id that are used by the dept in the plan
     @plan.departments.each do |dep|
        #loop through the staffings to find staffings with the location we want
        dep.staff.each do |staff|
          #now cross reference this current staffing's.loc_id with the list we have previously
          data.each do |k, v|
            # "location id thing " + staff.location_id.to_s                 
            if k.to_i == staff.location_id.to_i 
              v = Hash.new()
              v[dep.id.to_s] = staff
              %> <%= v.inspect + "data inspect #{data.inspect}"%>     <br /> <br />    <%      
            end                            
          end
        end        
     end
When I inspect the data of v, it looks good. But the inspection on data (the owner of v) shows nothing. What gives?

Lamont Cranston
Sep 1, 2006

how do i shot foam

Physical posted:

Is there something that I don't know that prevents me from assigning a value to a key in a hash.each loop?

code:
     #ok so we have our list of locations, now find the staff resources that have this id that are used by the dept in the plan
     @plan.departments.each do |dep|
        #loop through the staffings to find staffings with the location we want
        dep.staff.each do |staff|
          #now cross reference this current staffing's.loc_id with the list we have previously
          data.each do |k, v|
            # "location id thing " + staff.location_id.to_s                 
            if k.to_i == staff.location_id.to_i 
              v = Hash.new()
              v[dep.id.to_s] = staff
              %> <%= v.inspect + "data inspect #{data.inspect}"%>     <br /> <br />    <%      
            end                            
          end
        end        
     end
When I inspect the data of v, it looks good. But the inspection on data (the owner of v) shows nothing. What gives?

Just setting v won't do it; you'll have to do data[k] = (your new v).

(Though something tells me you could probably do this with inject instead. I'm not super familiar with the ins and outs but you might want to take a look.)

Lamont Cranston fucked around with this message at 01:05 on Mar 28, 2012

Physical
Sep 26, 2007

by T. Finninho

Lamont Cranston posted:

Just setting v won't do it; you'll have to do data[k] = (your new v).

(Though something tells me you could probably do this with inject instead. I'm not super familiar with the ins and outs but you might want to take a look.)

Yea thats the only way I found to do it so far and just moved on. It was kind of convoluted to do it that way I guess.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Physical posted:

Is there something that I don't know that prevents me from assigning a value to a key in a hash.each loop?

code:
     #ok so we have our list of locations, now find the staff resources that have this id that are used by the dept in the plan
     @plan.departments.each do |dep|
        #loop through the staffings to find staffings with the location we want
        dep.staff.each do |staff|
          #now cross reference this current staffing's.loc_id with the list we have previously
          data.each do |k, v|
            # "location id thing " + staff.location_id.to_s                 
            if k.to_i == staff.location_id.to_i 
              v = Hash.new()
              v[dep.id.to_s] = staff
              %> <%= v.inspect + "data inspect #{data.inspect}"%>     <br /> <br />    <%      
            end                            
          end
        end        
     end
When I inspect the data of v, it looks good. But the inspection on data (the owner of v) shows nothing. What gives?
Do you know that k represents the hash key, with v representing its related hash value?

First you are manipulating on a local object, v, so when you exit the scope of the block its just going to be erased.

Second, I don't know what the keys in data are since I can't see any input. But your loop is going to erase every single value in the hash and then create a hash as the new value wherein it contains the department's id correlating with the staff, but will subsequently overwrite that hash value everytime a staff has that department id (assuming you could even manipulate local variables). Without being able to see the actual data structures for each object, this seems really unstructured.

Lamont Cranston posted:

Just setting v won't do it; you'll have to do data[k] = (your new v).

(Though something tells me you could probably do this with inject instead. I'm not super familiar with the ins and outs but you might want to take a look.)

inject is essentially a reduce, how is that going to help him here? I am guessing you're referring to mapping?

Lamont Cranston
Sep 1, 2006

how do i shot foam

Strong Sauce posted:

inject is essentially a reduce, how is that going to help him here? I am guessing you're referring to mapping?

Well yes, but map returns an array. I was thinking he could do something like
code:
data.inject({}) do |hash, (k,v) | 
    #manipulate v however you want
    hash[k] = v
    hash
end
It at least avoids the problem of modifying the structure as your iterating over it.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

That seems like a lot of work done in the view layer. Physical have you tried moving some of that logic to the model to see if that simplifies things a bit?

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Lamont Cranston posted:

Well yes, but map returns an array. I was thinking he could do something like
code:
data.inject({}) do |hash, (k,v) | 
    #manipulate v however you want
    hash[k] = v
    hash
end
It at least avoids the problem of modifying the structure as your iterating over it.

Ah yes I kept thinking that the object returns as an array of hashes and not a hash. Still your solution doesn't actually modify `data`, it just returns a copy such that data is still not changed.

Adbot
ADBOT LOVES YOU

Lamont Cranston
Sep 1, 2006

how do i shot foam

Strong Sauce posted:

Ah yes I kept thinking that the object returns as an array of hashes and not a hash. Still your solution doesn't actually modify `data`, it just returns a copy such that data is still not changed.

True, but that's all I was really going for anyway.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply