Not sure what I'm doing wrong on this one. I've followed the Rails Cast for Carrierwave but am having a strange bug where the image isn't showing at all - the (HTML) source code is showing the image tag but nothing inside it.
Portfolio Model code:
class Portfolio < ActiveRecord::Base
validates :title, :content, presence: true
mount_uploader :feature_image, FeatureImageUploader
end
Feature Image Uploader code:
class FeatureImageUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png)
end
end
Show.html.haml code:
= #portfolio.title
=image_tag #portfolio.feature_image_url.to_s
=markdown(#portfolio.content).html_safe
And my form code:
.field
= f.label :title
%br
= f.text_field :title
.field
= f.label :date
%br
= f.datetime_select :date
.field
= f.label :content
%br
= f.text_area :content, rows: 10
.field
= f.label :feature_image
= f.file_field :feature_image
.actions
= f.submit
And my HTML source code is showing:
<img src=""/>
I've run my rake tests and everything is fine, no failures. Would someone mind having a look for me, would really appreciate it.
Thank you!
EDIT
This is my pastebin from the Server logs when I add a new portfolio entry - http://pastebin.com/1zNxB975
in views
=image_tag #portfolio.feature_image.url
and controller
portofolios_controller.rb
...
private
def portofolio_params
params.require(:portofolio).permit(:title, :date, :content, :feature_image)
end
not sure about the other params you might have and need, but :feature_image is a must.
Related
I am new to rails and I am trying to use the carrierwave gem to upload files onto my system. I have done all of the steps but struggling with how to code it so I am able to view it on my system without an error.
I have previously tried adding
show.html.erb:
<%= attachment_tag #post.attachment.url, class: "post-show" %>
but receive the error
"undefined method `attachment_tag' for #<#<Class:0xb646078>:0xb8bb8b0>"
posts.rb:
class Post < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
end
new.html.erb:
<%= f.label :attachment %><br>
<%= f.file_field :attachment %>
show.html.erb:
<%= attachment_tag #post.attachment.url, class: "post-show" %>
/uploaders/video_uploader.rb
class VideoUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
posts_controller:
def post_params
params.require(:post).permit(:post_id, :title, :body, :date, :image, :remove_image, :video, :attachment)
end
I expect the output of this to be a display of the file whether it is a pdf, ppt or word document.
EDIT:
<iframe src="#post.attachment.url"></iframe>
This was added to the show.html.erb instead of the attachment tag. I do not receive an error anymore but it displays this:
display on system once adding code
Alright, So I have days, tracks, and events. When I create a track, it is given the proper day_id along with its own track_id . When I try to create an event, I want it to be given the appropriate day_id and/or track_id.
So when I pull up a day it should only show the tracks and events that as associated with the day. An event should exist in a track, which exists in a day.
So, this is basically a calendar that shows a daily schedule of different tracks, and the events within the tracks.
Also, my events table in my db has a track_id and a day_id.
Here is my routes.rb
resources :days do
resources :tracks do
resources :events
end
end
My new/create methods from my events_controller.rb
def new
#day = Day.find(params[:day_id])
#track = Track.find(params[:track_id])
#new_event = Event.new
end
def create
#day = Day.find(params[:day_id])
#track = Track.find(params[:track_id])
#events = #track.events
#new_event = Event.new(params.require(:event).permit(:name,:start_time, :end_time))
if #new_event.save
flash[:notice] = "Saved"
redirect_to #day
else
flash[:error] = "Error"
render :new
end
end
And here is where I am trying to create a new event in my events.new.html.erb
<%= form_for [#day, #track, #new_event] do |f| %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control', placeholder: "Enter the event" %>
<%= f.label :start_time %>
<%= f.text_field :start_time, class: 'form-control', placeholder: "Enter a start time"%>
<%= f.label :end_time %>
<%=f.text_field :end_time, class: 'form-control', placeholder: "Enter a start time"%>
<%= f.submit "Save", class: 'btn btn-success' %>
<% end %>
Thanks for the help, I'm pretty sure I attached everything that was needed!
You should create the event from the track:
#new_event = #track.events.new
This will create an event with already the appropriate track_id inside.
However, this does work...
#new_event = #track.events.new(params.require(:event).permit(:name, :start_time, :end_time))
Please help me to resolve this error and reedit my all pages. Actually i am new to Ruby on Rails and i am using rails version-4 and ruby version-1.9.3.I want to show one form including select options and selected value saved in DB. My errors and code snippets explained below.
Error:
undefined method `email_providers=' for #<Class:0x4e68df0>
Extracted source (around line #2):
1 class Contact < ActiveRecord::Base
2 self.email_providers = %w[Gmail Yahoo MSN]
3 validates :email_provider, :inclusion => email_providers
4 end
views/contacts/index.html.erb
<%= form_for #contact,:url => {:action => "create"} do |f|%>
<%= f.text_field:gmail %>
<%= f.select :email_provider, options_for_select(Contact.email_providers, #contact.email_provider) %>
<%= f.submit "Submit"%>
<% end %>
controller/contacts_controller.rb
class ContactsController < ApplicationController
def index
#contact=Contact.new
end
def create
end
end
models/contact.rb
class Contact < ActiveRecord::Base
self.email_providers = %w[Gmail Yahoo MSN]
validates :email_provider, :inclusion => email_providers
end
migrate/20141222061313_create_contacts.rb
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :gmail
t.string :yahoo
t.string :msn
t.timestamps
end
end
end
I want to show the 3 content(gmail,yahoo,msn) in option drop down list and while it will be selected and clicked on submit button it will be saved in DB.Please help me to edit the code.Thanks in advance..
Change
self.email_providers = %w[Gmail Yahoo MSN]
validates :email_provider, :inclusion => email_providers
in your Contact model class to:
EMAIL_PROVIDERS = %w{Gmail Yahoo MSN}
validates :email_provider, inclusion: {in: EMAIL_PROVIDERS}
and the error should be fixed.
As you can guess, your Contact class doesn't have a self.email_providers= method. So trying to assign a value to it through this method will crash. What I've done is created a constant that can be easily accessed within the class through EMAIL_PROVIDERS and outside the class through Contact::EMAIL_PROVIDERS
I am while leraning how to use association in rails 4 application
I have a user having many opinions and I want to add user opinion in the book show page
This is how i proceed:
my user.rb
class User < ActiveRecord::Base
has_one :panier
has_many :opinions
end
opinion.rb
class Opinion < ActiveRecord::Base
belongs_to :user
end
views/books/show.html.erb
<h2>Votre opinion nous intéresse:</h2>
<%= form_for([#user, #user.opinions.build]) do |f| %>
<p>
<%= f.label :body, 'votre opinion' %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
opinion_controller.rb
class OpinionsController < ApplicationController
def create
#user = current_user
#opinion= #user.opinion.create(opinion_params)
end
private
def opinion_params
params.require(:opinion).permit(:body)
end
end
and in books_controllers this is my show method:
def show
#user= current_user
#books= Book.all
end
my routes:
get 'books/show' => 'books#show' , as: :books_list
resources :users do
resources :opinions
end
what I got as error:
undefined method `opinions' for nil:NilClass
in this line of code:
Most probably #user.opinions in your form causing this issue. check whether current_user returning object or not.
Also in your create method there is typo(#user.opinion), it should be #user.opinions.
Use accept nested attributes for same.
After trying for few hours I can not save to the database.
The context is this:
I have two types of users, one for that I only need very basic information [Username, email, password] and another kind of user for who I need a lot of information [age, gender, city and so on]
I did not use STI becouse of the vast quantity of Null values there would be in the table.
So I created this three modes in which a user has a profile (profiles table) or not depending of its type [1 or 2], and a field of this profile is the city this user is living in, that relates to another table in the DB, the cities table
class User < ActiveRecord::Base
has_one :profile
has_one :city, through: :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :city
[...a bunch of fields here]
end
class City < ActiveRecord::Base
has_many :profiles
has_many :users, through: :profiles
end
When I play with them in the rails console everything goes OK:
usr = User.new(name: "roxy", email: "roxy#example.me", password: "roxanna", password_confirmation: "roxanna", utype: 1)
cty = City.new(name: "Bucaramanga")
prf = Profile.new (rname: "Rosa Juliana Diaz del Castillo"...)
prf.city = cty
usr.profile = prf
usr.valid?
=> true
usr.save
=> true
but when I try to save in the app (View an Model)
<%= f.label :city, "En que ciudad te encuentras?"%>
<%= select_tag :city, options_from_collection_for_select(City.all, 'id', "name"),{:prompt => 'Selecciona tu ciudad'}%>
def new
#profile = Profile.new
end
def create
#profile = params[:profile]
#city= City.find_by_id(params[:city].to_i)
#profile.city = #city
end
I get this error:
undefined method `city=' for #<ActiveSupport::HashWithIndifferentAccess:0xa556fe0>
Can someone please help me?
UPDATE
As David suggested I created the Profile object in the first line of the create method, so my controller now look like this:
def create
#profile = Profile.new(params[:profile])
#city= City.find_by_id(params[:city].to_i)
#profile.city = #city
#usr = current_user
if #usr.profile.exists? #profile
#usr.errors.add(:profile, "is already assigned to this user") # or something to that effect
render :new
else
#usr.profile << #profile
redirect_to root_path
end
end
But I'm getting this error now
undefined method `exists?' for nil:NilClass
current_user returns the #current_user
def current_user
#current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
Could you tell me please, what am I doing wrong?
I want to write this to all of you who are beginning as well as I am and are stuck in this step.
I had to create a new project and play with it to realize what I was doing wrong. I figured out that I was validating a last time field I added to the Profiles table and had
# education :string(255) not null
but I had not added it yet to the form so the error launched is:
Failed to save the new associated so_profile.
Now, you know if you got this error, go check your schema and look for NOT_NULL fields you might be missing in the form, also you can comment out all your model validations and after it's working uncomment'em to be sure.
So, my Final Models:
class User < ActiveRecord::Base
has_one :profile
has_one :city, through: :profile
attr_accessible :email, :name
end
class Profile < ActiveRecord::Base
belongs_to :user
belongs_to :city
attr_accessible :age, :fcolor, :gender
end
class City < ActiveRecord::Base
has_many :profiles
has_many :users, through: :profiles
attr_accessible :name
end
My controllers:
class ProfilesController < ApplicationController
def new
#user = User.find_by_id(params[:id])
#profile = Profile.new
end
def create
#profile = Profile.new(params[:profile])
city = City.find_by_id(params[:city])
#profile.city = city
#user = User.find_by_id(params[:userid])
#user.profile = #profile
if #user.save
flash[:success] = "Guardado"
redirect_to profile_path(id: #user.id)
end
end
def show
#user = User.find(params[:id])
end
end
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
flash[:success] = "Registrado!"
redirect_to new_profile_path(id: #user.id)
else
flash[:error] = "No Registrado :("
redirect_to new
end
end
def show
#user = User.find_by_id(params[:id])
end
end
In a real app you have to use Cookies or something else to keep the session alive and therefore the user_token from where you get the user_id, but it works to play with associations.
The views:
profiles/new.html.erb
<%= #user.name %>
<%= form_for #profile, url: {action: :create, userid: #user.id } do |f| %>
<%= f.label :age, "Edad" %>
<%= f.text_field :age%> <br />
<%= label :city, "Ciudad"%>
<%= select_tag :city, options_from_collection_for_select(City.all, 'id', 'name')%>
<%= f.submit %>
<% end %>
profiles/show.html.erb
Hello <%= #user.name %><br />
Tu edad es: <%= #user.profile.age %><br />
Vives en <%= #user.profile.city.name%>
users/new.html.erb
<%= form_for #user do |f|%>
<%= f.label :name, "Nombre"%>
<%= f.text_field :name, size: 20, placeholder: "Escribe tu nombre aqui" %><br />
<%= f.label :email, "Email"%>
<%= f.text_field :email, size: 20, placeholder: "Escribe tu email aqui" %><br />
<%= f.submit "Sign me up!"%>
users/show.html.erb
Name: <%= #user.name %><br />
Email: <%= #user.email %>
And that's it!
Cheers.
Learn to read the error messages. The problem is that #profile is a hash because you didnt't actually create a new Profile object on the first line of the create method.
I think that the correct is
#so_profile.City
not
#so_profile.city
Because the class name is City