I wrote a small ruby script that generates an array like the one below:
{:title=>"Lorem ipsum",
:category=>["Lorem ipsum"],
:items=>
["Lorem ipsum",
"Lorem ipsum",
"Lorem ipsum"],
:process=>
["Sed ut perspiciatis unde omnis iste natus error."]}
How can I run that script in order to save the output into my rails database?
With a bit of guessing... you can write this is a rake task:
WeDontKnowWhichModelHere.create!({
:title => "Lorem ipsum",
:categories => [Category.new(:name => "Lorem ipsum"), ...],
:items => [Item.new(:name => "Lorem ipsum"), ...],
:processes => [Process.new(:name => "Sed ut perspiciatis unde omnis iste natus error")],
})
Related
I have a DB table name is the product. when I query (eloquent) to that table return collection object with all the fields. but I access the banner_image field every time return a null value.
but I can access the other variables in that collection working fine.
If I Defining An Accessor, the issue is solved. I want to know about, whats the issue only for one variable.
DD to eloquent collection
#original: array:20 [▼
"id" => 2
"type_id" => 2
"banking_id" => 1
"page" => "savings-accounts"
"url_slug" => "repellat-corporis-id-distinctio"
"title" => "{"en":"Mertz Underpass","si":"","ta":""}"
"short_description" => "{"en":"Ut laboriosam expedita qui repellat labore ut qui suscipit blanditiis fuga fugit et rerum.","si":"","ta":""}"
"interest_rate" => 40.9
"first_link_text" => null
"second_link_text" => null
"image" => "https://dummyimage.com/716x500"
"banner_image" => "https://dummyimage.com/716x500"
"banner_description" => "{"en":"Est placeat et aut laborum consequatur ab quas esse totam voluptatem et atque adipisci est quaerat aut et.","si":"","ta":""}"
"landing_page" => 0
"side_block" => null
"calculator" => null
"sort" => 0
"created_at" => null
"updated_at" => null
"deleted_at" => null
]
when I access the $innerProduct->banner_image (in controller) every time return null value.
I have found the issue. accidentally Ill added that column to translation array.
public $translatable = [
'title', 'short_description', 'first_link_text', 'second_link_text', 'banner_description','banner_image'
];
What I'm trying to do is find the URL's in comments and then check those URL's against an array. If the URL is in the array and has the key 'data' with a certain value then I want to replace each URL in the comment with custom text.
I have everything working except the replacing part. This is what I have so far.
the comment
Lorem www.link1.com and ipsum dolor sit amet, http://link2.com consectetur
adipiscing elit. Maecenas http://link3.com eu tempor nibh.
The array the function is using
Array
(
[0] => Array
(
[status] => 200
[data] => one
[url] => www.link1.com
)
[1] => Array
(
[status] => 204
[data] =>
[url] => http://link2.com
)
[2] => Array
(
[status] => 200
[data] => two
[url] => http://link3.com
)
)
the function
function check_the_status( $arrays, $comment ) {
// Bad statis types
$status = apply_filters( 'status_filter', array( 'one', 'two', 'three' ) );
$modified = '';
foreach( $arrays as $key => $array ){
$url = $array['url'];
$data = $array['data'];
if( in_array( $data, $status ) ) {
$modified = '<span>the new text</span>';
$the_comment = str_replace( $url, $modified, $comment );
}
}
return $the_comment;
}
the output
Lorem www.link1.com and ipsum dolor sit amet, http://link2.com consectetur
adipiscing elit. Maecenas "<span>the new text</span>" eu tempor nibh.
So, what's happening with this function, is it's only applying the new text to the last URL in the array, but I want it to be applied to the first and last URL's because they both have the data value I'm checking for in the array. I'm thinking the foreach loop isn't the right way to achieve what I want, but I'm not sure what's the best way.
The problem appears to be with the following line. You are starting over with each iteration by passing $comment each time:
$the_comment = str_replace( $url, $modified, $comment );
You should change it to:
$the_comment = str_replace( $url, $modified, $the_comment );
and intialize $the_comment before the loop:
$the_comment = $comment;
Based on additional comments, here's the working code. I added "bold" style so the result is more pronounced.
$arrays = Array
(
0 => Array
(
'status' => 200,
'data' => 'one',
'url' => 'www.link1.com'
),
1 => Array
(
'status' => 204,
'data' => '',
'url' => 'http://link2.com'
),
2 => Array
(
'status' => 200,
'data' => 'two',
'url' => 'http://link3.com'
)
);
function check_the_status( $arrays, $comment ) {
// Bad statis types
$status = apply_filters( 'status_filter', array( 'one', 'two', 'three' ) );
// The class for targeting the url
$span_class = apply_filters( 'status_class', 'sl-unsafe-link' );
$modified = '';
$the_comment = $comment;
foreach( $arrays as $key => $array ){
$url = $array['url'];
$data = $array['data'];
if( in_array( $data, $status ) ) {
$modified = '<span style="font-weight:bold">'.$url.'</span>';
$the_comment = str_replace( $url, $modified, $the_comment );
}
}
return $the_comment;
}
$comment = 'Lorem www.link1.com and ipsum dolor sit amet, http://link2.com consectetur adipiscing elit. Maecenas http://link3.com eu tempor nibh.';
$new = check_the_status($arrays, $comment);
echo $new;
I ran it locally and this is the output:
Lorem <span style="font-weight:bold">www.link1.com</span> and ipsum dolor sit amet, http://link2.com consectetur adipiscing elit. Maecenas <span style="font-weight:bold">http://link3.com</span> eu tempor nibh.
I'm struggling with this devise programming or configuration error in my app. The thing is is that when I login my application redirects me to the same page and not to the home. Also if I enter a wrong mail or wrong password, no error message comes out.
This is my routes.rb:
Smarket::Application.routes.draw do
get "home/index"
resources :tipo_transaccions
resources :producto_rematados
resources :provincia_units
resources :propiedadclases
resources :compra_venta_normals
resources :clase_units
resources :prod_of_necs
resources :compra_venta_especials
resources :producto_necesitados
resources :compra_remates
resources :notificacions
resources :comisions
resources :remates
resources :pujas
resources :valors
resources :usuarios
resources :propiedads
resources :regions
resources :productos
resources :estado_remates
resources :ganancia_liquidas
resources :est_prod_of_necs
resources :estado_notificacions
resources :producto_ofertados
resources :comunas
resources :condicions
root :to => "home#index"
devise_for :usuarios, :controllers => { registrations: 'registrations' }, :skip => [:sessions, :registrations]
as :usuario do
get "entrar", to: "devise/sessions#new", :as => :new_usuario_session
post "entrar", to: "devise/sessions#create", :as => :usuario_session
delete "salir", to: "devise/sessions#destroy", :as => :destroy_usuario_session
get "registrarse", to: "devise/registrations#new", :as => :new_usuario_registration
post "registrarse", to: "devise/registrations#create", :as => :usuario_registration
end
end
usuario.rb:
class Usuario < ActiveRecord::Base
mount_uploader :avatar, FotoUploader
include ActiveModel::Validations
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
self.table_name = 'usuario'
self.primary_key = 'usuario_id'
validates :usuario_nombre_usuario, :presence => true
validates :usuario_rut, :presence => true
validates :usuario_rut, rut: true
validates :usuario_nombre, :presence => true
validates :usuario_apellidopat, :presence => true
validates :usuario_apellidomat, :presence => true
validates :email, :presence => true
validates :usuario_calle, :presence => true
validates :usuario_numero_calle, :presence => true
validates :usuario_villa, :presence => true
belongs_to :usuario
belongs_to :comuna
and app/views/devise/session/new.html.erb:
<div class="login">
<div class="wrap">
<div class="col_1_of_login span_1_of_login">
<h4 class="title">New Customers</h4>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan</p>
<div class="button1">
<%= link_to "Crear cuenta", new_usuario_registration_path, :style => 'background: #555;
border:none;
color: #fff;
padding: 10px 20px;
cursor: pointer;
float: right;
font-family: "Exo 2", sans-serif;
outline: none;
font-size: 1em' %>
</div>
<div class="clear"></div>
</div>
<div class="col_1_of_login span_1_of_login">
<div class="login-title">
<h4 class="title">Login</h4>
<div id="loginbox" class="loginbox">
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => { :role => 'form'}) do |f| %>
<div>
<%= f.label :Email %><br />
<%= f.email_field :email, autofocus: true, :style => 'width:70%' %>
</div>
<div>
<%= f.label :Contraseña %><br />
<%= f.password_field :usuario_contrasena, autocomplete: "off", :style => 'width:70%' %>
</div>
<% if devise_mapping.rememberable? -%>
<div>
<%= f.check_box :remember_me %>
<%= f.label :remember_me, :style => 'float:left; outline: none; padding-right:10px; padding-top:3px; ' %>
</div>
<% end %>
<div><%= f.submit "Login", :style => 'background: #555;
border:none;
color: #fff;
padding: 10px 20px;
cursor: pointer;
float: right;
font-family: "Exo 2", sans-serif;
outline: none;
font-size: 1em'%></div>
<% end %><br>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
So for redirecting to other page after sign_in, you need to override devise method :
def after_sign_in_path_for resource
home_path
end
For error messages you need to set follow :
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => { :role => 'form'}) do |f| %>
<%= f.error_messages %>
........
This is my ContentSeeder.php
<?php
use App\Models\Page;
class ContentSeeder extends Seeder {
public function run()
{
DB::table('pages')->delete();
Page::create(array(
'title' => 'About us',
'slug' => 'about-us',
'body' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
'user_id' => 1,
));
Page::create(array(
'title' => 'Privacy Policy',
'slug' => 'privacy-policy',
'body' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
'user_id' => 1,
));
Page::create(array(
'title' => 'Terms of Use',
'slug' => 'terms-of-use',
'body' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
'user_id' => 1,
));
}
}
after running "php artisan db:seed" My first file works but not the second and i don't understand why.
Here is the following message:
PHP Fatal error: Class 'App\Models\Page' not found in C:\wamp\www\mysite\app\database\seeds\ContentSeeder.php on line 11
Here is my Page model located in app/models/Page.php
<?php
namespace App\Models;
class Page extends \Eloquent {
protected $table = 'pages';
/*public function author()
{
return $this->belongsTo('User');
}*/
}
It seems that you didn't update your Composer's autoload file. Any time you add a class to be called throughout Laravel, it needs to be included as a page loads. This can be done manually with an include() or require(), but you can also run php composer.phar dumpautoload (or composer autoload) to update which files are automatically loaded on each page. This needs to be done every time a class is added.
See Composer's autoloading documentation for more info.
It seems that, the problem has been solved but I just would like to mention that you may also use something like this:
class ContentSeeder extends Seeder {
public function run()
{
$pages = array(
array(
'title' => 'About us',
'slug' => 'about-us',
'body' => 'Lorem...',
'user_id' => 1,
),
array(
'title' => 'Privacy Policy',
'slug' => 'privacypolicy',
'body' => 'Lorem...',
'user_id' => 1,
)
// more...
);
DB::table('pages')->delete();
DB::table('pages')->insert($pages);
}
}
I would like to ask on how will I display this type of array in laravel blade view?
Array(
[0] => stdClass Object
(
[id] => 2
[email] => email#email.com
[username] => dodie
[firstname] => Jhon
[lastname] => David
[password] => $2y$08$x12gVo54SsUW0U1aHTHaXu7VbgHFG8So9.fd/DfczT7KOyk4J1nLS
[location] => {'long':47.061469, 'lat': 8.321743}
[photo] => 1.jpg
[hometown] => England
[Updated] => 1
[description] => "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
[role] => client
[deleted_at] =>
[created_at] => 2013-10-10 06:00:18
[updated_at] => 2013-10-10 07:24:22
[reviewer_id] => 1
[company_id] => 2
[title] => Very Bad Ass
[content] => badass
[review_rating] => 1
[helpful] => 0
[logo] => 2.jpg
[contactperson] => Jhon Doe
[companyname] => Hardy Contractor
[address] => makati Philippines
[type] => Heating and Airconditioning
[stars] => 2
[phone] => 554-9266
[fax] => Hardy Contractor
[website] => www.hardycontractors.com
)
This is how I pass this In my Controller:
$data = DB::select($query); //fetching data using Query Builder
return View::make('home')->with('users', $data);
this is how I call it on my blade view:
$users->website
Every time I call this on my blade
can you please enlighten me? :) I want to understand more on how I can handle this kind of problem.
What you have is an array of std class object.
In your view you can simply loop through them:
#foreach($users as $user)
{{ $user->website }}
#endforeach
In case you have one and only one object in the array, you might want to consider passing $users[0] to the view and then work with it as a single object.