PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label partial. Show all posts
Showing posts with label partial. Show all posts

Wednesday, May 18, 2022

[FIXED] How to pass local variable to partial from application layout in rails 3?

 May 18, 2022     layout, partial, partial-views, ruby-on-rails     No comments   

Issue

I have a couple of variables that need to be called in all controllers. Displaying latest news in the layout footer.

I create them in application_controller.rb

@hq_news_item = NewsItem.where(:branch_code => "CORP").first
@branch_news_item = NewsItem.where(:branch_code => "MN").first

In my layouts/application.html.haml

= render :partial => "layouts/footer_news"  , :hq_news_item => @hq_news_item, :branch_news_item => @branch_news_item

And then in my layouts/_footer_news I style them

= hq_news_item.title
= hq_news_item.author.name
... etc

Here is the thing, no matter what I do - it keeps saying that hq_news_item is undefined in partial.

All my other partials work fine. I think it has to do with the fact that it's a layout not a view. Can't find anything meaningful in the docs.

Any ideas?

Thank you.


Solution

I think you need to pass the variables as local variables to the partial:

= render :partial => "layouts/footer_news", :locals => { :hq_news_item => @hq_news_item, :branch_news_item => @branch_news_item }

Otherwise Rails won't really understand what you are passing as a variable to the partial and what you are passing as an argument to the render function.



Answered By - Pan Thomakos
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check if two string are a partial match in C#?

 May 18, 2022     c#, match, partial, string     No comments   

Issue

Possible Duplicate:
Are there any Fuzzy Search or String Similarity Functions libraries written for C#?

I am creating an application which will except user input of a Song or Artist or Album name and then will look through a String Array or ArrayList for any possible matches.

The auto suggestions will be calculated based on the match percentage.

For example

If user types link prk it should find Linkin Park or Link 80 or Link Wray but the match percentage will be different for all

Assume that the collection will only search for Artist names in Artist Collection and Song name in song collection.

(Percentage figures are just for explanation)

Linkin Park - 98%
Link Wray -82%
Link 80 - 62%

Solution does not have to be C# code, any regex or pseudo code will be good but should be implementable in C#.


Solution

Usually an implementation of the Levenshtein distance also called edit distance is used for this. This will find matches based on the minimum number of edits needed to transform one string into the other, counting all insertions, deletions, or substitutions of a single character as a measure for the "cost" - candidates are then strings that have the minimum cost.

Here's a link to an article with a generic implementation in C#.



Answered By - BrokenGlass
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to do OR search

 May 18, 2022     find, mongodb, partial, php     No comments   

Issue

I want to search for a partial first and last name match - for example in sql

f_name LIKE J%   OR  l_name LIKE S%   

would match John Smith or John Henry or Harry Smith .

I am assuming I may need to use the "$or" operator,

I have this so far that I believe is doing the LIKE % part properly, but I believe it is doing an "AND" search (meaning it searches for f_name LIKE J% AND l_name LIKE S% so it would only match John Smith):

$name1="J";
$name2="S";
$cursor = $this->clientCollection->find(array('f_name' => new MongoRegex('/^'.$name1.'/i'), 'l_name' => new MongoRegex('/^'.$name2.'/i') ));

Note: This will match containing as in %J%

MongoRegex('/'.$name1.'/i')

This will match starts with (notice the added ^) as in J%

MongoRegex('/^'.$name1.'/i')

Solution

$or takes an array of clauses, so you basically just need to wrap another array around your current query:

array('$or' => array(
    array('f_name' => new MongoRegex('/'.$name1.'/i')), 
    array('l_name' => new MongoRegex('/'.$name2.'/i'))
));

Edit: the previous example missed an inner set of array() calls.

The original, wrong, example that I posted looked like this:

array('$or' => array(
    'f_name' => new MongoRegex('/'.$name1.'/i'), 
    'l_name' => new MongoRegex('/'.$name2.'/i')
));

This is a valid query, but not a useful one. Essentially, the f_name and l_name query parts are still ANDed together, so the $or part is useless (it's only getting passed one query, so it's the same as just running that query by itself).

As for the alternative you mentioned in your comment, that one doesn't work because the outermost array in a query has to be an associative array. The confusion arises because Mongo's query syntax is JSON-like and uses a mixture of objects and arrays, but both of those structures are represented in PHP by arrays. The PHP Mongo driver basically converts PHP associative arrays to JSON objects ({ ... }), and "normal" PHP arrays to JSON arrays ([ ... ]).

The practical upshot is that "normal" PHP arrays are generally only valid when inside an associative array, like when specifying multiple values for a field. The following example from the PHP Mongo manual shows a valid usage of a "normal" array in a query:

$cursor = $collection->find(array("awards" => array('$in' => array("gold", "copper"))));


Answered By - John Flatness
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I get this variable to be defined?

 May 18, 2022     partial, ruby, ruby-on-rails, ruby-on-rails-3, variables     No comments   

Issue

I have this code:

  <% @registered_friends.each do |friend| %>    
      <li><%= render 'profiles/fb_follow_form' %></li>
  <% end %>

It renders a partial in a different directory with this line:

<% if current_user != nil && current_user.following?(friend) %>

However my app is telling me that friend is undefined? How do I give myself access to the variable?


Solution

Changing <li><%= render 'profiles/fb_follow_form' %></li>

to <li><%= render 'profiles/fb_follow_form', :friend => friend %></li>

should do it



Answered By - AaronThomson
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to include a partial in app template (symfony)

 May 18, 2022     partial, php, symfony1     No comments   

Issue

I have created a template home.php in app/frontend/templates/home.php

I include this template if my user isn't connected. I try to include 2 partials :

<?php echo get_partial('sfGuardAuth/signin_form', array('form' => $form)) ?>
<?php echo get_partial('news/listNews', array('listNews' => $listNews)) ?>

But when I want to use variables $form and $listNews, I have errors :

Notice: Undefined variable: form

Notice: Undefined variable: listNews

Why ?


Solution

Using components resolves the problem



Answered By - Elorfin
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to incrementally load an asp.net page having a Repeater control?

 May 18, 2022     asp.net, controls, partial, rendering, repeater     No comments   

Issue

I have a page that shows results of a query. The results are displayed using a Repeater control that emits a div element that holds text data and images related to that particular result. The problem is that the page takes considerable amount of time to load partly because of the huge amount of processing required to generate the data.

So, is there a way to improve the page load by incrementally rendering the page rather than the have the user wait until the full data is available

I was thinking about sending the text data of each result first, and then as the images are available, send them to client to be displayed with each result. I guess I will need to use AJAX, but I'm not exactly sure how to get this done.

Does anyone have any suggestions or experience with this situation?

Thanks,


Solution

If you are going to control the flow, you can set up flushing on the binding event so the data is flushed out prior to having everything. But that may not be the best option; and, with standard tagged documents (rather than CSS docs) it might not help anyway, as the browser may not render even when flushed (depends on the tags in the Repeater).

Another option is retrieving via AJAX and flusing as data comes in (or at least showing a "wait for it" graphic). The wait graphic can be done without AJAX, but the load with AJAX pattern is well documented.

You can also limit the amount of data on a single page, unless this is a report of some type.



Answered By - Gregory A Beamer
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to render a partial from another namespace in Rails 3?

 May 18, 2022     partial, ruby-on-rails-3     No comments   

Issue

In my Rails 3 project I have:

namespace :admin do
  resources :users
end

scope :frontend do
  resources :users
end

There is a partial with filename "/views/admin/users/_form_fields.html.haml".

And I want to render it from "/views/frontend/users/_form.html.haml".

This code doesn't work:

render 'admin/users/form_fields', :f => f

Solution

To pass local variables you need this sintax:

render :partial => "/admin/users/form_fields", :locals => { :f => f }

Hope this helps. you can take a look to Rails Guide: Using Partials



Answered By - JCorcuera
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can tweaks to existing methods in an auto-generated C# partial class be persisted?

 May 18, 2022     c#, code-generation, overriding, partial, sealed     No comments   

Issue

I am working with Visual Studio Coded UI Tests, and wish to persist tweaks to the generated code.

The code is generated as a partial class in UIMap.cs and UIMap.Designer.cs, and so I know one solution would be to create a method with a slightly different name, such as myMethod_persist in UIMap.cs and use this instead of myMethod in UIMap.Designer.cs, which will be overwritten every time the source is regenerated.

This however seems very messy, and so what I'd prefer, is to instead override myMethod in UIMap.cs. This way the interface is not complicated with lots of gumph, and I don't have to remember to change every instance of myMethod in calling code to myMethod_persist

Unfortunately when it comes to C# I'm a bit of a noob, and don't even know if this is possible.

Basically what I want is this:

[UIMap.Designer.cs]
partial class myClass
{
    public override void myMethod( int a ){ somethingHorrible(int a); };
}

[UIMap.cs]
partial class myClass
{
    public sealed override void myMethod( int a ){ somethingNice(int a); };
}

But I know that the sealed and override keywords are usually used with derived subclasses classes, not partial classes. Is this possible? If not then what would be my best alternatives?


Solution

If you have no control over the auto-generation itself (ie. a framework or 3rd party generator) your options are somewhat limited. The two approaches that come to mind are to modify the generated code--which as you noted is not practical for changes that are significant and perhaps accumulating over time--and/or to create a derived class and use that instead of using the auto-generated class directly (assuming you control the code which would be using them, which seems likely).

A derived class (inheriting the auto-generated class) would be able to use override or new in the method declarations you want to replace. However, there are a lot of caveats to this approach as well. You can only "override" a method that was delcared as virtual in the base class (or was itself an override of another underlying virtual base, etc). You can also replace a method with a "new" one in the derived class, but the other code in the base class will not know about your "new" version and will not call it (whereas they will call your "override" because they know the method to be virtual). There are also issues of accessiblity; your derived class won't have access to private members of the base class.

But for some set of things you want to do it could work. In some cases you might have to tweak the auto-generated code slightly such as adding the keyword "virtual" or changing "private" members to "protected" so that you can access them from your derived class.

Added: Of course, you can also add new members to the original generated class in your own permanent file for the same partial class, and this code would have access to the class's private members. That can be another way to give your derived class access to the private members, such as by creating a protected property to wrap access to a private member field. If you didn't need to make changes to existing methods you wouldn't necessarily need to create a derived class, but your example talked about wanting to "override" methods from the auto-generated code, so presumably they already exist there.

Also note that a Designer file--such as for a Form or UserControl--does not usally get completely overwritten, so cautious changes outside the core generated code (eg. not inside the "Windows Form Designer generated code" region) can be made (and are persisted). For example, it is sometimes necessary to add a call to your own custom clean-up method in the Dispose(...) method in the Designer file.



Answered By - Rob Parker
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use @Html.Partial() directly on a page in MVC 3

 May 18, 2022     asp.net-mvc-3, partial, partial-views     No comments   

Issue

I want to use @Html.Partial("_partialView") to include a partial view on my page in MVC 3.

Both the page and the viewmodel have a viewmodel; thus, the following error is generated:

The model item passed into the dictionary is of type '[...]page', but this dictionary requires a model item of type '[...]partialview'.

How can I use the @Html.Partial() method while keeping the two viewmodels?


Solution

You should use this overload that allows the model object to be passed to partial view

    public static MvcHtmlString Partial(
      this HtmlHelper htmlHelper,
      string partialViewName,
      Object model
    )

By the way, do you really need to call Partial? RenderPartial is better - it writes directly to the response stream(compared to partial that returns string), so reserves the memory. Partial views can be quite big, so there's memory overhead with Partial if you do not absolutely need it.



Answered By - archil
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I render a child partial inside its parents partial?

 May 18, 2022     nested, partial, render, ruby-on-rails     No comments   

Issue

I have tables of venues, reviews and comments where a venue can have many reviews and a review can have many comments.

The reviews themselves are shown as partials on the venues show page using:

<%= render :partial => 'reviews/review', :collection => @venue.reviews %>

I thought using this:

<%= render :partial => 'comments/comment', :collection => @review.comments %>

inside the review partial would succesfully show the comments for that particular review but its just not displaying anything and giving no errors.

using <%= review.comments.count %> in the review partial does correctly show the number of comments added and checking the comments records in the console shows they have the correct foreign keys.

Any help is much appreciated!


Solution

"did you tried changing @review to review in second one? – rubish Jul 25 at 22:48"



Answered By - Dave
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access attributes in a partial of a nested rails form?

 May 18, 2022     forms, nested-forms, partial, ruby-on-rails-3     No comments   

Issue

I want to use the boolean attribute is_white from my inner_object to switch between html code in the the partial _inner_object_form_fields. This is my attempt.

<%= form_for @outer_object do |f| %>
  <%= f.fields_for :inner_object do |builder| %>
    <%= render :partial => "inner_object_form_fields", :locals =>  { :f => builder } %>
  <% end %>
<% end %>

This is my attempt of the partial _inner_object_form_fields.

<% if f.is_white == true %>
  <%= f.label(:name, "White") %>
<% else %>
  <%= f.label(:name, "Black") %>
<% end %>

This is the migration file of InnerObjects.

class InnerObjects < ActiveRecord::Migration
  def self.up
    create_table :inner_objects do |t|
      t.string "name"
      t.boolean "is_white", :default => true
      t.timestamps
    end
  end
  def self.down
    drop_table :inner_objects
  end
end

I found a similar question but could not retrieve an answer for me. The question is: How can access the attribut is_white? My example does NOT work.


Solution

Try

<% if f.object.is_white == true %>

Seem to remember you could access the object this way (not 100% sure though ;)



Answered By - oliverbarnes
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Where to put view logic?

 May 18, 2022     .net, asp.net-mvc, partial, views     No comments   

Issue

I am a little confused regarding the design patterns of ASP.NET MVC. I have a Masterpage including a partial view that renders breadcrumbs:

<div id="header">
    <strong class="logo"><a href="#">Home</a></strong>
    <% Html.RenderPartial("BreadCrumbs"); %>

The thing is, I want the breadcrumb links to work both in production and in my dev environment. So my code in the partial view goes something like this:

<p id="breadcrumbs">
    You are here: <a href="http://
    <% if (Request.Url.IsLoopback)
           Response.Write(String.Format("{0}/{1}", Request.Url.Host, Request.Url.Segments[1]));
       else
           Response.Write("http://mysite.com/");

...

Is this violating the principle of keeping the view "stupid"? Part of my reasoning for extracting this from the masterpage was this principle. Seems that I just moved the problem over to a new view? What is the alternative?


Solution

Not sure what MVC version you are using. If you are using MVC3, you could create a GlobalActionFilter: http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-global-action-filters.aspx

public class ViewBagInjectionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnResultExecuting(filterContext);

        filterContext.Controller.ViewBag.SiteUrl = filterContext.HttpContext.Request.Url.IsLoopback
                                                       ? String.Format("{0}/{1}",
                                                                       filterContext.HttpContext.Request.Url.Host,
                                                                       filterContext.HttpContext.Request.Url.
                                                                           Segments[1])
                                                       : "http://mysite.com/";

    }
}

This filter could then add a property into your ViewBag (which is a dynamic object), called SiteUrl, in which you set the site url depending on the state you are in.

In your PartialView you would no longer need the if statement, and just call: ViewBag.SiteUrl . In addition any other page will have access to the SiteUrl property.



Answered By - Gideon
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to partial search over lucene index? (search some documents, not all)

 May 18, 2022     indexing, lucene, partial, search     No comments   

Issue

Not sure if the tittle is correct for the purpose, but what i want is to be able to search only few documents (and not all) from a lucene index.

Think about it as the following context:

The user wants to search inside a book, which is indexed on lucene, chapter by chapter (every chapter corresponds to a document). The user needs to be able to select the chapters he wants to search in, avoiding irrelevant occurences for his study.

Is that possible to restrict the search to only some documents? or do i have to search ALL index and then filter the results?

Thank you!


Solution

Lucene allows you to apply Query Filters, so that you can restrict the results only for those which match the filter criteria.
So basically you can search for chapter:chapter1 and the search will be limited only for chapter one documents



Answered By - Jayendra
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to substring a text easily

 May 18, 2022     c#, html, partial, substring, text     No comments   

Issue

Alright here the question. This is an example text

Nokia 700<span>Stok Kodu: 389952</span>
<br><span style="background-image:none; margin:0; padding:0; font:14px/18px Arial,Helvetica,sans-serif">Nokia 700 Cep Telefonu PDA, Dokunmatik, Bluetooth, Radyo</span>

I want to get "Nokia 700" which starts with index 0 and ends with <span> and i am able to do it with the way below

var singleNode = myDoc.DocumentNode.SelectSingleNode(srxProductName);
string srProductName = singleNode.InnerHtml.ToString()
    .Substring(0, singleNode.InnerHtml.ToString().IndexOf("<span>"));

The question is i wonder are there any easier or more practical way of doing it.


Solution

If you already have the node containing your text in singleNode, you can just extract the first child node, which should be a text node, and get its value:

var productName = singleNode.ChildNodes[0].Value;


Answered By - Jacob
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you not do partial mocking in this scenario?

 May 18, 2022     java, mocking, partial, unit-testing     No comments   

Issue

Let's say I wrote a pretty simple class called ValueFinder that looks like this:

public class ValueFinder {

    public String findValue(Object obj) {
        String value = null;
        value = findValueFirstWay(obj);
        if (value == null) {
            value = findValueSecondWay(obj);
        }
        return value;
    }

    protected String findValueFirstWay(Object obj) {
        ....
    }

    protected String findValueSecondWay(Object obj) {
        ....
    }
}

Now I want to test that findValueFirstWay is really the first method attempted when calling findValue. This is a very simple class, the "algorithms" of the ways are very simple. Without doing a partial mock where findValueFirstWay and findValueSecondWay are mocked and findValue is left alone, how do I test that?

I assume I'm supposed to refactor the class so that findValueFirstWay and findValueSecondWay are in a separate class or classes? It just seems like unnecessary work for something so simple.


Solution

You could avoid mocking entirely and test it by the visible effect with real objects.

Or you could mock the objects being passed in as values, and expect whatever calls that the findValueFirstWay(Object obj) makes to the obj that cause it to return a null, etc.

However, even though it seems simple, my first impulse would still be to extract the problem methods to a separate class or two, so that the interaction can be more naturally tested with mocks.



Answered By - Don Roby
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What "boundary conditions" can make a rectangle "look" like a circle?

 May 18, 2022     boundary, differential-equations, partial, wolfram-mathematica     No comments   

Issue

I am solving a fourth order non-linear partial differential equation in time and space (t, x) on a square domain with periodic or free boundary conditions with MATHEMATICA.

WITHOUT using conformal mapping, what boundary conditions at the edge or corner could I use to make the square domain "seem" like a circular domain for my non-linear partial differential equation which is cartesian?

The options I would NOT like to use are:

  • Conformal mapping
  • changing my equation to polar/cylindrical coordinates?

This is something I am pursuing purely out of interest just in case someone screams bloody murder if misconstrued as a homework problem! :P


Solution

That question was asked on the time people found out that the world was spherical. They wanted to make rectangular maps of the surface of the world...

It is not possible.

The reason why is not possible is because the sphere has an intrinsic curvature, while the cube/parallelepiped has not. It can be shown that for two elements with different intrinsic curvatures, their surfaces cannot be mapped while either keeping constant infinitesimal distances, either the distance between two points is given by the euclidean distance.

The easiest way to understand this problem is to pick some rectangular piece of paper and try to make a sphere of it without locally stretch it or compress it (you can fold). You can't. On the other hand, you can make a cylinder surface, because the cylinder has also no intrinsic curvature.

In maps, normally people use one of the two options:

  1. approximate the local surface of the sphere by a tangent plane and make a rectangle out of it. (a local map of some region)

  2. make world maps but implement some curved lines everywhere identifying that the measuring distances must be made according to those lines.

This is also the main reason why when traveling from Europe to North America the airplanes seems to make a curve always trying to pass near canada. If we measured the distance from the rectangular map, we see that they should go on a strait line to minimize the distance. However, because we are mapping two different intrinsic curvatures, the real distance must be measured in a different way (and not via a strait line).

For 2D (in fact for nD) the same reasoning applies.



Answered By - Jorge Leitao
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why do I have this "undefined method form" with my RoR app?

 May 18, 2022     forms, partial, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

I have a partial

= form.fields_for :cycles do |c|
  %tr{:style=>"border-right:none;"}
%td{:width=>"16%"}
  = c.text_field :day, :size=>6
  = c.hidden_field :id
%td{:width=>"35%"}= c.text_field :hour, :size=>15
%td{:width=>"35%"}= c.text_field :hour_night, :size=>15
%td{:style => "width:7%;padding:0;border-right:none",:align=>"center"}
  = c.hidden_field :_destroy
  = link_to image_tag("panel_tools/delete.png",:size=>"15x15"), nil, :href =>"", :onclick => "check_nested_attr_destroy(this);return false;" 

I call this from the view like this

= form_for(@schedule_of_working, @new_action ? {:url => schedule_of_workings_path} : {:url => schedule_of_working_path, :method=> :put}) do |f| 
.....
= render(:partial=>'cycles', :collection => @schedule_of_working.cycles, :locals => {:form => f}) if @schedule_of_working.cycles.count > 0

I'm getting an error about undefined method form..

rails -v 3.1.0


Solution

Rails only really works well when you follow its conventions.

You should avoid using: hidden fields, put with a form, passing in the action that way and I'm not sure what you are trying to do with the url in various parts, but anyway avoid these unless you have really good reason why you are not structuring it according to convention. Focus more on your routes and how resources are setup and your models and their relationships and your views should be very minimalist. In them I'm not sure what the hour and hour_night are, or theor length 15. Confusion mix of stuff.

So your form, as is, has a few problems. Rather than specific advice I would just say re-write it. It should be much simpler than this. I would recommend watching some railscasts on forms, e.g.
Forms Part one, two or three



Answered By - Michael Durrant
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I pass a collection from a parent partial to an arbitrary sub-partial depth?

 May 18, 2022     partial, ruby-on-rails     No comments   

Issue

I'm following the RailsTutorial, and I'm currently stuck on exercise 10.5.5. Since I'm changing quite a bit, I've put the code into a paste (updated).

There are a few things to note before going into the paste:

  1. One of the original partials receives a collection from it's "parent" partial, while the other receives the object directly from the controller.
  2. The if statement in both of these "child" partials uses a different object name, but they're represent the same object in the database.

Ideally, I'd like to move the if statement into the grandchild, or sub-sub-, partial. I can leave it in the child partial if need be, but this doesn't feel DRY.

I've tried rendering the grandchild partial with <%= render partial: 'shared/foo', object: bar, as: :baz %> so I can use baz in the grandchild partial, since the other child partial uses baz by default. In that partial, I'm just doing <%= render partial: 'shared/foo', object: baz %>. Confused? Me, too.

You'll notice I've tried rendering the partials both with and without passing in the parent object. Maybe the parent object needs to be redefine? I also just tried <%= render partial: 'shared/micropost_delete_link', object: feed_item %>, but no luck.

Each approach I've tried so far yields the same error in the tests:

 Failure/Error: before { visit root_path }
 ActionView::Template::Error:
   undefined method `user' for :feed_item:Symbol

This seems to indicate that I can't pass a single object received from the parent option collection: @feed_items.

Update: There was a typo in my original paste. With that fixed in the updated paste, my tests are still failing.

 Failure/Error: before { visit root_path }
 ActionView::Template::Error:
   undefined method `user' for nil:NilClass

Solution

Somewhere along the line, I tried a different syntax, and the tests started passing:

<%= render partial: 'shared/micropost_delete_link', locals: { micropost: feed_item } %>

Even though the docs say the following should be equivalent:

<%= render :partial => "account", :object => @buyer, :as => 'user' %>
<%= render :partial => "account", :locals => { :user => @buyer } %>

Testing is still a bit unusual for me, so I can't rule out that it forced something in the suite to be re-evaluated.



Answered By - jrhorn424
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I yield a "future" content_for tag in Rails 3?

 May 18, 2022     content-for, partial, ruby-on-rails-3, templates, yield     No comments   

Issue

I have a template with 2 partials. In the first one, I am yieleding content which is only defined in the second partial (with a content_for tag). The problem is that the yield does not recognize that content yet since it was not defined.

If I reverse the order of the partials the yield recognized the content, yet the layout is not as I desire obviously...

Is there a way to do this? Thank you.


Solution

Okay, this was actually an easy fix. I moved the second partial into a content_for block placed above the first partial, and then just yielded it instead of declaring it as a partial.



Answered By - Indigon
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how do i place this ruby code correctly?

 May 18, 2022     erb, partial, ruby, ruby-on-rails, ruby-on-rails-3     No comments   

Issue

I have a piece of code which displays a complicated 'listing' of resources. by complicated i mean that it has name, date, time posted, number of comments, picture, description, and tons more things that you obviously only want to write that block of code one time.

I'm trying to think of how this would go into the rails architecture and I'm at a loss

i need to display the resource listing using a different variable in different controllers. currently its in a partial called _resource_view.html.erb

This is fine for the main listing, but its not usable for the persons profile listing, which takes the same format but shows different resources

_resources_expanded.html.erb

<ul class="res-list">
  <% @resources.each do |resource| %>
    ... list stuff
  <% end %>
</ul>

It uses @resources on index, but on the profile page it uses the same listing code except its @user.resources.each do |resource|

I was thinking maybe something like this but this seems redundant .. and im not even sure if it will work

<ul class="res-list">
  <% @resources.each do |resource| %>
    <%= render 'layouts/resources_expanded' %>
  <% end %>
</ul>

Solution

Don't use instance variables, use local variables in the partial - that lets you pass in a single each time through the @resources.each loop.

<%= render 'layouts/resources_expanded', :resource => resource %>

and then in _resource_view.html.erb change @resource to resource



Answered By - DGM
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing