Populate a Scaffold via Seed - ruby-on-rails

I have an Item's Scaffold which has approximately 200+ Item's which are pre-fix.
So adding them manually is really painful.
Can i populate the Scaffold in my seed-file and then db:seed on production ?
I don't know the proper method but i think it's something like this:
items = Item.create([
{ name: 'css' },
{ name: 'css3' },
{ name: 'ruby' },
{ name: 'rails' },
{ name: 'python' },
{ name: 'html' }
])
I'm searching for a Solution that will seed my Item's Scaffold...

Try the following code by adding remaining items in array in db/seeds.rb file and run rake db:seed command. That generates expected records in items table.
['css','rubyonrails','java'].each do |item|
Item.find_or_create_by_name(:name => item)
end
Good luck.

You have to do it that way, but you don't need to asign it to the items variable.
You just have to add to the seed.rb file the code with your items. I've added the delete_all before to avoid creating duplicate items.
Item.delete_all
Item.create([
{ name: 'css' },
{ name: 'css3' },
{ name: 'ruby' },
{ name: 'rails' },
{ name: 'python' },
{ name: 'html' }
])
And then you'll have to seed your database with rake:db seed.

Related

GatsbyJS + Netlify CMS Issue with relative path

I am trying to add new projects to my GatsbyJS site using Netlify CMS. The problem is that my code is using relative path to reach the thumb images but when uploading a new thumb image from netlify it saves it as an absolute path. This is causing a problem and I dont understand what it is exactly. Is Gatsby not able to read the absolute path that is being received from the CMS? If that could be the problem, how could i make that the CMS gives me a relative path?
Any help will be much appreciated :)
This is the path in my markdown files:
thumb: ../images/thumbs/memory.png
This is the path created by the CMS:
/src/images/thumbs/img_2370.jpg
This is my config.yml
backend:
name: git-gateway
branch: master # Branch to update (optional; defaults to master)
publish_mode: editorial_workflow
media_folder: "src/images/thumbs"
collections:
- name: "projects" # Used in routes, e.g., /admin/collections/blog
label: "Projects" # Used in the UI
folder: "src/projects" # The path to the folder where the documents are stored
create: true # Allow users to create new documents in this collection
slug: "{{slug}}" # Filename template, e.g., YYYY-MM-DD-title.md
fields: # The fields for each document, usually in front matter
- { label: "Title", name: "title", widget: "string" }
- { label: "Stack", name: "stack", widget: "string" }
- { label: "Slug", name: "slug", widget: "string" }
- { label: "Url", name: "url", widget: "string" }
- { label: "Publish Date", name: "date", widget: "datetime" }
- { label: "Thumb", name: "thumb", widget: "image" }
- { label: "Body", name: "body", widget: "markdown" }
This is a "known issue" that Netlify should fix soon (it has been 2 years since it has been spotted so far). Netlify doesn't support relative paths hence the image paths are broken.
Consider using the following solutions:
gatsby-plugin-netlify-cms-paths adding the following in your gatsby-config.js:
module.exports = {
plugins: [
// Including in your Gatsby plugins will transform any paths in your frontmatter
`gatsby-plugin-netlify-cms-paths`,
// Including in your Remark plugins will transform any paths in your markdown body
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
`gatsby-plugin-netlify-cms-paths`,
],
},
},
],
}
gatsby-remark-relative-images-v2 by adding:
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
// gatsby-remark-relative-images-v2 must
// go before gatsby-remark-images
{
resolve: `gatsby-remark-relative-images-v2`,
},
{
resolve: `gatsby-remark-images`,
options: {
// It's important to specify the maxWidth (in pixels) of
// the content container as this plugin uses this as the
// base for generating different widths of each image.
maxWidth: 590,
},
},
],
},
},
Check that media_folder and public_folder are properly configured:
media_folder: src/images/thumbs
public_folder: /images/thumbs
Note the starting slash in the public_folder and double-check that those are the correct ones.

ActiveRecord: Skip validation when saving multiple objects

I know I can skip validations for an individual save, like this:
User.new(name: 'John').save(validate: false)
But how can I do that when saving multiple objects at once? Like this:
Category.create([
{ name: 'Apps' },
{ name: 'Songs' },
{ name: 'Movies' }
])
I found this gem: https://github.com/zdennis/activerecord-import
It works like this:
categories = [
Category.new(name: 'Apps'),
Category.new(name: 'Songs'),
Category.new(name: 'Movies')
]
Category.import(categories, validate: false)
It is also possible to use plain arrays instead of ActiveRecord objects.
I guess it generates pure SQL when validate is set to false so it can skip validations.
You can't do that with create. If you really must skip validations you can do something like this:
[
{ name: 'Apps' },
{ name: 'Songs' },
{ name: 'Movies' }
].each do |attributes|
c = Category.new(attributes)
s.save(validate: false)
end

Seeding in Ruby on Rails

I have several deeply nested models and I would like to seed my database. The models are as following: Each restaurant has many menus. Each menu has many categories. Each category has many meals. Currently, my seed looks like this:
restaurant_seed = [
{
name: "KFC",
address: "Sofia",
description: "Fast food.",
phone_number: "88888888"
}
]
menu_seed = [
{
name: 'Spring menu.',
active: true
},
}
name: 'Winter menu.',
active: false
}
]
category_seed = [
{
name: "Dessert",
available_all_day: false,
age_restriction: false,
category_avatar: File.open(File.join(Rails.root, "app/assets/images/desserts.jpg"))
},
{
name: "Salad",
available_all_day: true,
age_restriction: false,
category_avatar: File.open(File.join(Rails.root, "app/assets/images/salads.jpeg"))
}
]
meal_seed = [
{
name: "Shopska salata",
meal_avatar: File.open(File.join(Rails.root, "app/assets/images/shopska_salad.jpg"))
},
{
name: "Shisha",
meal_avatar: File.open(File.join(Rails.root, "app/assets/images/shisha.jpg"))
}
]
However, I do not know how to actually seed the database with that info. The idea is that each restaurant will have all of the menu seeds, each of the menus in each restaurant will have each category from the category seed and so on. Thank you for any suggestions!
Write a method to iterate all seeds and create corresponding records.
def setup_restaurants(restaurant_seed, menu_seed, category_seed, meal_seed)
restaurant_seed.each do |r_seed|
restaurant = Restaurant.create(r_seed)
menu_seed.each do |m_seed|
menu = restaurant.menus.create(m_seed)
category_seed.each do |c_seed|
category = menu.categories.create(c_seed)
meal_seed.each do |mm_seed|
category.meals.create(mm_seed)
end
end
end
end
end

Mixed Chart Types using Chartkick/Highcharts on Rails

I'm trying to create a mixed column/line chart using Highcharts.
I've been trying to use the library functionality to set one of my data series to be of type "line". I have tried a few different approaches, but I can't seem to figure out how to pass the type parameter of a given series using the Highcharts API.
<%= column_chart( ChartData.new(#forecast).revenue_and_net_income, library: {
title: {
text: "Revenue and Net Income"
},
series: [{
1 => {
type: "line"
}
}],
} ) %>
Where my data come from the following method:
def revenue_and_net_income
data = [
{
name: "Revenue",
data: revenue_by_year
},
{
name: "Net Income",
data: net_income_by_year,
}
]
end
Not sure what I'm doing wrong? I only seem to be able to access the Highcharts API methods listed under 'Chart', none of the series options etc. seem to work. Can anyone point me in the right direction for how to successfully get this to work?
you can try this way.
<%= line_chart [
{
name: "Amount", type: "column", data: #cause.donations.map {
|t| [t.user.name, t.amount]
}
},
{
name: "Test", type: "line", data: #cause.donations.map {
|t| [t.user.name, t.amount]
}
}
],
prefix: "$",
adapter: "highcharts"
%>
just don't care line_chart, column_chart or anythings... ONLY custom type in data. OK

extjs editor grid update rails

i am trying to update records displayed in editor grid..but instead of updating same record, a new record gets inserted into the database...what am i missing??pllzz help..following is my JsonStore code :
Ext.data.Api.restActions = {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy : 'DELETE' };
ProdStore = Ext.extend(Ext.data.JsonStore, {
constructor: function(cfg) {
cfg = cfg || {};
ProdStore.superclass.constructor.call(this, Ext.apply({
storeId: 'ProdStore',
id:'ProdStore',
url: 'products.json',
root: 'proddata',
restful:true,
idProperty:'id',
successProperty:'success',
autoLoad:true,
autoSave:false,
batch:true,
writer: new Ext.data.JsonWriter({
encode: false,
listful: false,
writeAllFields: false}),
fields: [
{ name:'customer_id'},{ name: 'prodnm'},
{ name: 'qty'}, { name: 'rate' }, { name: 'amt'}
]
}, cfg));
}
});
new ProdStore();
The idProperty set on the store should be the field that represents unique rows in the database. Perhaps customer_id in this case?
If this does not fix the issue, I would have to see the back end code to see how the save is being handled.

Resources