I have a CarrierWave rails uploader. I want to seed the database with fake users so I'm trying to add the images in with the same seed file. The images are in a common storage, so if I can just get the avatar strings in the database they'll work. When it saves the users though the image's aren't sticking.
# db/seeds.rb
user1 = User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => "v1357014344/bdylan.jpg"
user1.save
# IRB
User.first
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
> a = User.first
> a.avatar = "v1357014344/bdylan.jpg"
> a.save
(10.7ms) commit transaction
=> true
> a
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
You will have to insert the data in the following way.
File.open(File.join(Rails.root, 'test.jpg'))
So the entire user create would look like
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => open("v1357014344/bdylan.jpg")
Related question
Besides using open() as Nishant suggestions, you can also specify remote_avatar_url to manually set the remote URL.
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :remote_avatar_url => "http://upload.wikimedia.org/wikipedia/commons/2/28/Joan_Baez_Bob_Dylan_crop.jpg"
Thanks to JosephJaber for suggesting this in Seeding file uploads with CarrierWave, Rails 3
I used this approach to populate some video URLs for CarrierWave Uploader in my seeds.rb
To update the database directly and skip out on CarrierWave:
model[:attribute] = 'url.jpg'
model.save
Related
I am newbie in Ruby, I am trying to install one app that says:
lobsters$ rails console
Loading development environment (Rails 4.1.8)
irb(main):001:0> User.create(:username => "test", :email => "test#example.com", :password => "test", :password_confirmation => "test", :is_admin => true, :is_moderator => true
irb(main):002:0> Tag.create(:tag => "test")
When I run rails console, it outputs "create some file" So how do I create user?
Try this :
User.create!(username: "test", email: "test#example.com", password: "test", password_confirmation: "test", is_admin: true, is_moderator: true)
In practice, Ruby programmers reserve ! to adorn the names of methods that do something unexpected, or perhaps a bit dangerous
So in this case, the "unexpected" result is that an exception is
raised instead of just failing and returning false.
I'm trying to upload an image file to my rails server, but I keep hitting a wall.
This is my form themed_controller/new ,
= form_for(#campaign, validate: true, :html => {:multipart => true}) do
.form-group
%label.col-sm-3.control-label
Campaign Name
.col-sm-6
%input#title.form-input{ name: "#campaign[campaign_title]", placeholder: "Campaign Title", required: "", type: "text", value: ""}/
.form-group
%label.col-sm-3.control-label
Campaign Description
.col-sm-6
%textarea.form-input{ name: "#campaign[campaign_description]", placeholder: "Campaign Description", required: "", value: ""}
.form-group
%label.col-sm-3.control-label
Pick stories
.col-sm-6
%select#themed_campaign_live_story_ids{name: "#campaign[live_story_ids][]", :multiple => true, :required=> true, value: []}
-# = f.select 'live_story_ids[]', [], :multiple => true
#date-range
.form-group#valid-from
%label.col-sm-3.control-label
Campaign runs from
.col-sm-6
%input.form-input#themed_campaign_valid_from{ name: "#campaign[valid_from]",:class => 'jquery-ui-date valid-from', :data => {:provide =>"datepicker", :behaviour => "datepicker"}, required: "", type: "text", value: ""}/
.form-group#valid-till
%label.col-sm-3.control-label
Campaign runs till
.col-sm-6
%input.form-input#themed_campaign_valid_till{ name: "#campaign[valid_till]",:class => 'jquery-ui-date valid-till', :data => {:provide =>"datepicker", :behaviour => "datepicker"}, required: "", type: "text", value: ""}/
.form-group#valid-till
%label.col-sm-3.control-label
Upload cover (1280x350)
.col-sm-6
-#upload-image.btn.btn-medium.btn-green{ :data => {:url => "/campaign/upload"} }
#upload-image
%input#image_media{name: "#campaign[cover]", type: "file"}/
.form-group
.col-sm-offset-3.col-sm-6
%button.form-button.btn-large.btn-green.btn#campaign-submit{type: "submit"}
Set up Campaign
And this is my create method
def create
campaign = params[:#campaign]
campaign['added_by_email'] = current_user.email
#campaign = ThemedCampaign.create(campaign)
if #campaign.save
img_attr = params[:#campaign]['cover']
image = Campaign.new img_attr
#campaign.cover = image
Resque.enqueue(ImageQueue,image.id)
#render :json => image.to_jq_upload.to_json
end
redirect_to '/admin/themecampaign'
end
I have created a seperate uploader for this,
# encoding: utf-8
class CampaignUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# storage :fog
before :cache, :save_original_filename
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg png)
end
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/campaigns/#{model.id}/"
end
end
And this is my campaign modal, which hold the image
class Campaign
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
include Rails.application.routes.url_helpers
mount_uploader :cover, CampaignUploader
end
Now when I upload the form I keep getting an undefined methodempty?' for #
> NoMethodError - undefined method `empty?' for
> #<ActionDispatch::Http::UploadedFile:0x00000109968c50>: () Users/skmvasu/.rvm/gems/ruby-2.0.0-p451/bundler/gems/mongoid-bc72426681d5/lib/mongoid/attributes/processing.rb:21:in
> `process_attributes' ()
> Users/skmvasu/.rvm/gems/ruby-2.0.0-p451/bundler/gems/mongoid-bc72426681d5/lib/mongoid/document.rb:111:in `block in initialize' ()
> Users/skmvasu/.rvm/gems/ruby-2.0.0-p451/bundler/gems/mongoid-bc72426681d5/lib/mongoid/threaded/lifecycle.rb:84:in
> `_building' ()
> Users/skmvasu/.rvm/gems/ruby-2.0.0-p451/bundler/gems/mongoid-bc72426681d5/lib/mongoid/document.rb:105:in `initialize' actionpack (4.0.2)
> lib/action_dispatch/routing/url_for.rb:104:in `initialize'
> app/controllers/themed_campaign_controller.rb:57:in `new'
> app/controllers/themed_campaign_controller.rb:57:in `create'
Essentially, this blows up while trying to call Campaign.new with the image attributes. I thought the image field was nil but when I inspected the img_attr from the server, I noticed the uploaded file was present and the temp field was corretly pointing to a local copy.
When I dug deeper, I noticed the the cover filed in my themed_controller was invalid.
MOPED: 127.0.0.1:27017 INSERT database=mangoweb_development collection=themed_campaigns
documents=[{"_id"=>BSON::ObjectId('53ba605c5661731da8060000'),
"campaign_title"=>"Test campaign", "campaign_description"=>"Test
campaign desciption", "live_story_ids"=>["53a9b3e5566173146e030000",
"5343eafc5661731195030000", "5343eacc566173117f030000",
"5343eadf5661731189030000"], "valid_from"=>2014-07-07 00:00:00 UTC,
"valid_till"=>2014-07-22 00:00:00 UTC,
"cover"=>"#",
"added_by_email"=>"xxxxxxxxx",
"campaign_sane_title"=>"Test-campaign", "updated_at"=>2014-07-07
08:54:52 UTC, "created_at"=>2014-07-07 08:54:52 UTC}] flags=[]
COMMAND database=mangoweb_development command={:getlasterror=>1, :w=>1}
runtime: 11.9600ms
#
What am I doing wrong here?Why is the value of cover is a String version of the uploaded Object reference, instead of the file values, and why the Image not getting created?
I've been over this issue for the last 2 days, and have looked at various references. I know, I must be doing something very silly, but I'm not able to get it.
Please help me with this issue. Thanks in advance.
You can use form instance object to easily handle this
Change
form_for(#campaign, validate: true, :html => {:multipart => true}) do
to
form_for(#campaign, validate: true, :html => {:multipart => true}) do |f|
and use f while referencing the form fields
%textarea.form-input{ name: "#campaign[campaign_description]", placeholder: "Campaign Description", required: "", value: ""}
should be changed to
f.text_area :campaign_description, placeholder: "Campaign Description", required: "", value: ""
and for the file field
f.file_field :cover
Let me know if that works
I have a CarrierWave rails uploader. I want to seed the database with fake users so I'm trying to add the images in with the same seed file. The images are in a common storage, so if I can just get the avatar strings in the database they'll work. When it saves the users though the image's aren't sticking.
# db/seeds.rb
user1 = User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => "v1357014344/bdylan.jpg"
user1.save
# IRB
User.first
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
> a = User.first
> a.avatar = "v1357014344/bdylan.jpg"
> a.save
(10.7ms) commit transaction
=> true
> a
=> #<User id: 1, email: "test1#test.com", name: "Bob Dylan", avatar: nil>
You will have to insert the data in the following way.
File.open(File.join(Rails.root, 'test.jpg'))
So the entire user create would look like
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :avatar => open("v1357014344/bdylan.jpg")
Related question
Besides using open() as Nishant suggestions, you can also specify remote_avatar_url to manually set the remote URL.
User.create :email => "test1#test.com", :password => "testing", :name => "Bob Dylan", :remote_avatar_url => "http://upload.wikimedia.org/wikipedia/commons/2/28/Joan_Baez_Bob_Dylan_crop.jpg"
Thanks to JosephJaber for suggesting this in Seeding file uploads with CarrierWave, Rails 3
I used this approach to populate some video URLs for CarrierWave Uploader in my seeds.rb
To update the database directly and skip out on CarrierWave:
model[:attribute] = 'url.jpg'
model.save
Any idea on how to create and save a new User object with devise from the ruby console?
When I tried to save it, I'm getting always false. I guess I'm missing something but I'm unable to find any related info.
You can add false to the save method to skip the validations if you want.
User.new({:email => "guy#gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" }).save(false)
Otherwise I'd do this
User.create!({:email => "guy#gmail.com", :roles => ["admin"], :password => "111111", :password_confirmation => "111111" })
If you have confirmable module enabled for devise, make sure you are setting the confirmed_at value to something like Time.now while creating.
You should be able to do this using
u = User.new(:email => "user#name.com", :password => 'password', :password_confirmation => 'password')
u.save
if this returns false, you can call
u.errors
to see what's gone wrong.
When on your model has :confirmable option this mean the object user should be confirm first. You can do two ways to save user.
a. first is skip confirmation:
newuser = User.new({email: 'superadmin1#testing.com', password: 'password', password_confirmation: 'password'})
newuser.skip_confirmation!
newuser.save
b. or use confirm! :
newuser = User.new({email: 'superadmin2#testing.com', password: 'password', password_confirmation: 'password'})
newuser.confirm!
newuser.save
If you want to avoid sending confirmation emails, the best choice is:
u = User.new({
email: 'demo#greenant.com.br',
password: '12feijaocomarroz',
password_confirmation: '12feijaocomarroz'
})
u.confirm
u.save
So if you're using a fake email or have no internet connection, that'll avoid errors.
None of the above answers worked for me.
This is what I did:
User.create(email: "a#a.com", password: "asdasd", password_confirmation: "asdasd")
Keep in mind that the password must be bigger than 6 characters.
I looked through the YAML for ruby documentation and couldn't find an answer.
I have a list of several employees. Each has a name, phone, and email as such:
Employees:
Name | Phone | Email
john 111 a#b.com
joe 123 b#a.org
joan 321 c#a.net
How would I write the above information in YAML to end up with the following ruby output?
employees = [ {:name => 'john', :phone => '111', :email => 'a#b.com'}, {:name => 'joe', :phone => '123', :email => 'b#a.org'}, {:name => 'joan', :phone => '321', :email => 'c#a.net'} ]
This is how I parse the YAML file:
APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")
Thank you!
- name: john
phone: 111
email: a#b.com
- name: joe
phone: 123
email: b#a.org
- name: joan
phone: 321
email: c#a.net
Output is string keys, not symbol keys, but you can make that conversion yourself if really necessary.
Note that standard yaml which ships with Ruby 1.8.6 is NOT UTF / Unicode safe.
Use either Ruby 1.9 yaml or Ya2YAML gem if you'll have any non-ASCII test.
Also, the easiest way to see what the yaml input should be is to create (in Ruby irb), an example of your data structure. Then turn it into yaml text by using the .to_yaml object class method.
Eg
require 'yaml'
# create your structure
a = [{'name' => "Larry K", 'age' => 24,
'job' => {'fulltime' => true, 'name' => 'engineer'}}]
a.to_yaml
=> "--- \n- name: Larry K\n job: \n name: engineer\n fulltime: true\n age: 24\n"
# then substitute line breaks for the \n:
---
- name: Larry K
job:
name: engineer
fulltime: true
age: 24