Actually I want to display all data of Magazine model on the admin side page But i got the following error while tried to fetch all data on the admin side(i.e.http://localhost:3000/homes/magazineissue).I also want to display some value belongs to User model through user's id.
Error:
NoMethodError in HomesController#magazineissue
undefined method `user_id' for #<Array:0x2780b98>
Rails.root: C:/Site/library_management1
Application Trace | Framework Trace | Full Trace
app/controllers/homes_controller.rb:100:in `magazineissue'
My codes are as follows.
views/homes/magazineissue.html.erb:
<% if admin_signed_in? %>
<div class="bar">
Logged in as <strong><%= current_admin.email %></strong>.
<%= link_to 'Edit profile', edit_admin_registration_path, :class => 'navbar-link' %> |
<%= link_to "Logout", destroy_admin_session_path, method: :delete, :class => 'navbar-link' %>
</div>
<% else %>
<%= link_to "Sign up", new_admin_registration_path, :class => 'navbar-link' %> |
<%= link_to "Login", new_admin_session_path, :class => 'navbar-link' %>
<% end %>
<div class="big-container">
<div class="admin-image">
<div class="bpaddingdiv1"><img src="/assets/admin.png" border="0" name="admin" /></div>
</div>
<div class="borderlightgreen"></div>
<div class="admin-name">
<div class="tpaddingdiv2 textaligncenterdiv"><img src="/assets/adminpanel.png" border="0" name="admin" /></div>
</div>
<div class="leftside">
<div id="leftsidebtn">
<ul>
<li>Manage Books</li>
<li><a href="/homes/userissues" >User Issues</a></li>
<li><a href="/homes/magazineissue" >Magazine Issues</a></li>
</ul>
</div>
</div>
<div class="middlebox">
<center>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Email Id</th>
<th>Magazine Name</th>
<th>Magazine Title</th>
<th>Purchased on</th>
<th>CD/DVD</th>
</tr>
</thead>
<tbody>
<% #magazines.each do |magazine| %>
<tr>
<td><%= #users.first_name %></td>
<td><%= #users.email %></td>
<td><%= magazine.mag_name %></td>
<td><%= magazine.mag_title %></td>
<td><%= magazine.purchased_on %></td>
<td><%= magazine.cd_dvd %></td>
</tr>
<% end %>
</tbody>
</table>
</center>
</div>
</div>
views/controller/homes_controller.rb:
class HomesController < ApplicationController
before_filter :authenticate_admin!,only: [:admin]
def index
end
def admin
end
def managebooks
#books=Book.new
if params[:id]
#books=Book.find(params[:id])
#book=Book.all
end
end
def savebooks
#books=Book.new(params[:books])
if #books.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'managebooks',:id => #books.id
else
flash[:notice]="Data couldnot submitted successfully"
flash[:color]="invalid"
render 'managebooks'
end
end
def remove
#books=Book.find(params[:id])
#books.destroy
end
def books
end
def showbooks
#books=Book.all
end
def searchbooks
#books=Book.all
end
def member
#users=User.new
end
def registration
#users=User.new
end
def savedata
#users=User.new(params[:users])
if #users.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data could not submitted successfully"
flash[:color]="invalid"
render 'registration'
end
end
def issuebooks
#issues=Issue.new
end
def savedissuebooks
#issues=Issue.new(params[:issues])
if #issues.save
flash[:notice]="information has saved successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data couldnot saved"
flash[:color]="invalid"
render 'issuebooks'
end
end
def availablebooks
#books=Book.all
end
def userissues
#issues=Issue.all
end
def magazine
#magazines=Magazine.new
end
def savemagazines
#users=User.find(params[:id])
#magazines=Magazine.new(params[:magazines])
#magazines.user_id=#users.id
if #magazines.save
flash[:notice]="Data submitted successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:notice]="Data could not saved"
flash[:color]="invalid"
render 'magazines'
end
end
def magazineissue
#magazines=Magazine.all
#users=User.find(#magazines.user_id)
end
end
db/migrate/20150317084229_create_magazines.rb
class CreateMagazines < ActiveRecord::Migration
def change
create_table :magazines do |t|
t.string :mag_name
t.boolean :cd_dvd
t.decimal :cost, :precision => 8, :scale => 2
t.date :purchased_on
t.string :mag_title
t.integer :user_id
t.timestamps
end
end
end
model/magazine.rb
class Magazine < ActiveRecord::Base
attr_accessible :cd_dvd, :cost, :mag_name, :mag_title, :purchased_on
belongs_to :user
end
model/user.rb
class User < ActiveRecord::Base
attr_accessible :address, :email, :first_name, :last_name, :password, :password_hash, :password_salt, :tel_no ,:password_confirmation
attr_accessor :password
before_save :encrypt_password
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :first_name, :presence => true, :length => {:in => 3..10}
validates :last_name , :presence => true , :length => {:in => 3..10}
validates :tel_no , :presence => true , :length => {:in => 1..10}
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
has_many :issue
has_many :book
has_many :magazine
end
Please help me to resolve this error.
As you have defined:
#magazines = Magazine.all
It results an Array that contains all the magazines.
Now in your HomeController you are doing:
#magazines.user_id
Which throws:
undefined method `user_id' for #<Array:0x2780b98>
because as mentioned above #magazines is an Array.
Solution to this can be to select a particular Magazine object from the returned #magazines Array and proceed.
A quick example can be:
#users=User.find #magazines.first.user_id
# However this is just for sake of example.
# You may want to select an object from the Array more wisely.
The problem is in controller in line you already mentioned - let's take a look:
def magazineissue
#magazines=Magazine.all
#users=User.find(#magazines.user_id)
end
In here you are fetching an Array of Magazines - the Array doesn't have an id method. What I guess you would like to do is something like:
def magazineissue
#magazines=Magazine.all
#users=User.find(#magazines.map(&:user_id))
end
To fetch Users by ALL Magazines.
Let me know if it helped!
UPDATE
From the comments we had it looks like you're trying to achieve something like:
def magazineissue
#magazines=Magazine.includes(:user).all
end
And in your view, change the <table> to:
<table>
<thead>
<tr>
<th>First Name</th>
<th>Email Id</th>
<th>Magazine Name</th>
<th>Magazine Title</th>
<th>Purchased on</th>
<th>CD/DVD</th>
</tr>
</thead>
<tbody>
<% #magazines.each do |magazine| %>
<tr>
<td><%= magazine.user.first_name %></td>
<td><%= magazine.user.email %></td>
<td><%= magazine.mag_name %></td>
<td><%= magazine.mag_title %></td>
<td><%= magazine.purchased_on %></td>
<td><%= magazine.cd_dvd %></td>
</tr>
<% end %>
</tbody>
</table>
Good luck!
Related
I am getting the following error while i am submitting the form.
Error:
ActiveRecord::MultiparameterAssignmentErrors in HomesController#savemagazines
1 error(s) on assignment of multiparameter attributes
Rails.root: C:/Site/library_management1
Application Trace | Framework Trace | Full Trace
app/controllers/homes_controller.rb:85:in `new'
app/controllers/homes_controller.rb:85:in `savemagazines'
The below are my code snippets.
views/homes/magazines.html.erb:
<% if current_user %>
<div class="totaldiv">
<div class="navdiv"><span>Purchase Magazines</span> <span>Logged in as <%= current_user.email %></span></div>
<div class="wrapper">
<div id="leftsidebtn">
<ul>
<li>Book issue</li>
<li>Books Available</li>
<li>Magazines Purchase</li>
<li>Log Out</li>
</ul>
</div>
</div>
<div class="restdiv" id="ex3" >
<center>
<div class="container">
<%= form_for :magazines,:url => {:action => 'savemagazines'} do |f| %>
<p>
<label for="mg_name">Enter Magazine Name:</label>
<%= f.select(:mag_name,options_for_select([['Business India ','Business India'],['Business Today ','Business Today '],['Forbes India ','Forbes India '],['Time magazine Asia ','Time magazine Asia '],['Electronics For You','Electronics For You']],selected: "magazine"), { include_blank: true }) %>
</p>
<p>
<label for="mag_title">Enter Magazine Title</label>
<%= f.text_field :mag_title,placeholder:"Enter magazine title" %>
</p>
<p>
<%= f.check_box :cd_dvd,{},true,false %> CD/DVD
</p>
<p>
<label for="purchase">Purchase Date</label>
<%= f.date_select :purchased_on %>
</p>
<p>
<%= f.submit "submit",:class => "btn btn-success" %>
</p>
<% end %>
</div>
</center>
</div>
</div>
<% end %>
controller/homes_controller.rb
class HomesController < ApplicationController
before_filter :authenticate_admin!,only: [:admin]
def index
end
def admin
end
def managebooks
#books=Book.new
if params[:id]
#books=Book.find(params[:id])
#book=Book.all
end
end
def savebooks
#books=Book.new(params[:books])
if #books.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'managebooks',:id => #books.id
else
flash[:notice]="Data couldnot submitted successfully"
flash[:color]="invalid"
render 'managebooks'
end
end
def remove
#books=Book.find(params[:id])
#books.destroy
end
def books
end
def showbooks
#books=Book.all
end
def searchbooks
#books=Book.all
end
def member
#users=User.new
end
def registration
#users=User.new
end
def savedata
#users=User.new(params[:users])
if #users.save
flash[:notice]="Data has submitted successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data could not submitted successfully"
flash[:color]="invalid"
render 'registration'
end
end
def issuebooks
#issues=Issue.new
end
def savebooks
#issues=Issue.new(params[:issues])
if #issues.save
flash[:notice]="information has saved successfully"
flash[:color]="valid"
redirect_to :action => 'member'
else
flash[:notice]="Data couldnot saved"
flash[:color]="invalid"
render 'issuebooks'
end
end
def availablebooks
#books=Book.all
end
def userissues
#issues=Issue.all
end
def magazine
#magazines=Magazine.new
end
def savemagazines
#magazines=Magazine.new(params[:magazines])
if #magazines.save
flash[:notice]="Data submitted successfully"
flash[:color]="valid"
redirect_to :action => "member"
else
flash[:notice]="Data could not saved"
flash[:color]="invalid"
render 'magazines'
end
end
end
20150317084229_create_magazines.rb
class CreateMagazines < ActiveRecord::Migration
def change
create_table :magazines do |t|
t.string :mag_name
t.boolean :cd_dvd
t.decimal :cost, :precision => 8, :scale => 2
t.string :datetime
t.string :mag_title
t.timestamps
end
end
def down
create_table :magazines do |t|
t.string :purchased_on
end
end
end
Please check my code and let me to know where i did the mistake and solution as well.
I am getting the following error while trying to do reset password by sending sending the link to email and open that link from that email.
Error:
NoMethodError in Admins#editpass
Showing C:/Site/swargadwar_admin/app/views/admins/editpass.html.erb where line #16 raised:
undefined method `Password_field' for #<ActionView::Helpers::FormBuilder:0x21c0108>
Extracted source (around line #16):
13: <% end %>
14: <p>
15: <label for "new_pass">New Password :</label>
16: <%= f.Password_field :password,placeholder:"Enter your new password" %>
17: </p>
18: <p>
19: <label for "new_pass">Confirm New Password :</label>
Rails.root: C:/Site/swargadwar_admin
Application Trace | Framework Trace | Full Trace
app/views/admins/editpass.html.erb:16:in `block in _app_views_admins_editpass_html_erb___904659562_17338176'
app/views/admins/editpass.html.erb:2:in `_app_views_admins_editpass_html_erb___904659562_17338176'
Please check my below codes and let me to know where i did the mistake as well as try to help me to resolve this.
views/admins/editpass.html.erb
<center>
<%= form_for :admin,:url => {:action => "setpass",:id => params[:id] } do |f| %>
<% if #admin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#admin.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #admin.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for "new_pass">New Password :</label>
<%= f.Password_field :password,placeholder:"Enter your new password" %>
</p>
<p>
<label for "new_pass">Confirm New Password :</label>
<%= f.Password_field :password_confirmation,placeholder:"confirm your new password" %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
</center>
controller/admins_controller.rb
class AdminsController < ApplicationController
def create_registration
#admin=Admin.new(params[:admin])
if #admin.save
flash[:notice]="User has created successfully"
flash[:color]="valid"
redirect_to :action => "index" , :controller => 'homes'
else
flash[:alert]="User could not created"
flash[:color]="invalid"
render 'homes/index'
end
end
def forget
#admin=Admin.new
end
def resetpass
#admin=Admin.find_by_email(params[:admin][:email])
if #admin.email==params[:admin][:email]
UserMailer.registration_confirmation(#admin).deliver
flash[:notice]="Check your email to reset the password"
flash[:color]="valid"
redirect_to :action => "index" , :controller => 'homes'
else
flash[:alert]="Invalid email id"
flash[:color]="invalid"
render 'homes/index'
end
end
def editpass
#admin=Admin.new
end
def setpass
#admin=Admin.find(params[:id])
if #admin.update_attributes(params[:admin])
flash[:notice]="Your password has updated successfully"
flash[:color]="valid"
redirect_to :action => "index" , :controller => 'homes'
else
flash[:alert]="Your password could not updated"
flash[:color]="invalid"
render 'homes/index'
end
end
end
model/admin.rb
class Admin < ActiveRecord::Base
attr_accessible :email, :password_hash, :password_salt, :picture, :user_name,:password_confirmation,:password, :remember_me
attr_accessor :password
attr_accessor :remember_token
before_save :encrypt_password
mount_uploader :picture, PictureUploader
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :user_name, :presence => true, :length => {:in => 3..10}
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
has_secure_password
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def Admin.digest(string)
cost = 10
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def Admin.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = Admin.new_token
update_attribute(:remember_digest, Admin.digest(remember_token))
end
def forget
update_attribute(:remember_digest, nil)
end
end
Please help me.
You just have a typo: The method is named password_field, not Password_field. Just change the two method calls in app/views/admins/editpass.html.erb and you are done.
Please anyone help me to resolve the following error.Actually I want to show the exit values those present in DB on the text field in edit page.But i am getting some error.
Error:
NoMethodError in Users#edit
Showing C:/Site/edit/app/views/users/edit.html.erb where line #4 raised:
undefined method `each' for #<User:0x3ac9ea8>
Below are my code snippets
views/users/index.html.erb:
<h1>This is index page</h1>
<center>
<p>Enter data</p>
<div class="option">
<p><%= link_to "Click here to enter data",users_new_path %></p>
<p><%= link_to "Display data",users_show_path%></p>
</div>
</center>
views/users/show.html.erb
<h1>Show your data</h1>
<center>
<ul>
<% #user.each do |t| %>
<li>
<%= t.name %> |
<%= t.email %> |
<%= t.password%> |
<%= t.created_at %>
<%= link_to "edit",users_edit_path(:id => t.id) %> || <%= link_to "Reset Password",users_reset_path(:id => t.id) %>
</li>
<% end %>
</ul>
<div class="back_btn">
<button type="button" class="btn-custom " style="cursor:pointer;">Back</button>
</div>
</center>
views/users/edit.html.erb
<h1>Edit your data here</h1>
<center>
<%= form_for #user ,:url => {:action => "update",:id => params[:id]} do |f| %>
<% #edit.each do |t| %>
<div class="div_reg">
<p>
<label for="username" class="uname" data-icon="u" >username </label>
<%= f.text_field:name, :input_html => {:value => t.name}%>
</p>
<p>
<label for="username" class="uname" data-icon="u" >Email </label>
<%= f.text_field:email,:input_html => {:value => t.email} %>
</p>
<p>
<label for="username" class="uname" data-icon="u" >Password </label>
<%= f.password_field:password,:input_html => {:value => t.password} %>
</p>
<p>
<label for="username" class="uname" data-icon="u" >Password </label>
<%= f.password_field :password_confirmation %>
</p>
<center>
<%= f.submit "Update",:class => 'btn-custom' %>
</center>
<div class="back_btn">
<button type="button" class="btn-custom " style="cursor:pointer;">Back</button>
</div>
</div>
<% end %>
<% end %>
</center>
<% if #user.errors.any? %>
<ul class="Signup_Errors">
<% for message_error in #user.errors.full_messages %>
<li><%= message_error %></li>
<% end %>
</ul>
<% end %>
controller/users_controller.rb
class UsersController < ApplicationController
def index
end
def new
#user=User.new
end
def create
#user=User.new(users_param);
if #user.save
flash[:notice]="You signed up successfully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="You have not signed up successfully"
flash[:color]="invalid"
redirect_to :action => 'new'
end
end
def show
#user=User.all
end
def edit
#user=User.new
#edit=User.find(params[:id])
end
def update
flash[:notice]=params[:id]
#user=User.find(params[:id])
if #user.update_attributes(update_params)
flash[:notice]="Your data is updated succesfully"
flash[:color]="valid"
redirect_to :action => 'show'
else
flash[:alert]="Your data could not update,Please check it..!!"
flash[:color]="invalid"
redirect_to :action => 'edit'
end
end
def reset
#user=User.new
end
def emailsend
#user=User.find(params[:id])
if #user.email== params[:user][:email]
UserMailer.registration_confirmation(#user).deliver
flash[:notice]="Check your email to reset the password"
flash[:color]="valid"
redirect_to :action => 'reset'
else
flash[:notice]="Check your valid email or your email is not found"
flash[:color]="invalid"
redirect_to :action => 'show'
end
end
def resetpass
#user=User.new
end
def passres
#user=User.find_by_email(params[:user][:email])
if #user.update_attributes(updates_password)
flash[:notice]="Your password id updated succefully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="Your data could not update..Please check it..!!"
flash[:color]="invalid"
redirect_to :action => 'show'
end
end
private
def users_param
params.require(:user).permit(:name, :email, :password,:password_confirmation)
end
def update_params
params.require(:user).permit(:name,:email,:password,:password_confirmation)
end
def updates_password
params.require(:user).permit(:email,:password,:password_confirmation)
end
end
model/user.rb
class User < ActiveRecord::Base
#attr_accessor :password
#attr_accessor :name
#attr_accessor :email
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name, :presence => true, :uniqueness => true, :length => { :in => 3..20 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
end
Please help me to resolve this error.Thanks in advance.
#edit.each is your problem. You have a User instance here not an ActiveRecord array of Users therefore .each isn't available.
You can remove the iteration <% #edit.each do |t| %> and change all references t to #edit ie. #edit.name.
Please help me to solve this error.When update action is executing this error is showing.
Error:
NoMethodError in UsersController#update
undefined method `permit' for :user:Symbol
My code snippets are given below.
views/users/edit.html.erb
<h1>Edit your data</h1>
<%= form_for #user,:url => {:action => 'update',:id => params[:id]} do |f| %>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field:name,:value => #edit.name %>
<%= f.email_field:email,:value => #edit.email %>
<%= f.text_field:message,:value => #edit.message %>
<%= f.submit "Update" %>
<% end %>
<%= link_to "Back",users_index_path %>
controller/users_controller.rb
class UsersController < ApplicationController
def index
end
def new
#user=User.new
end
def create
#user=User.new(users_params)
if #user.save
flash[:notice]="Your data is saved succesfully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="You are entering wrong data"
flash[:color]="invalid"
render :new
end
end
def show
#user=User.all
end
def delete
#user=User.find(params[:id])
if #user.delete
flash[:notice]=#user.name+"has deleted successfully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]=#user.name+"could not delete.Please check it.."
flash[:color]="invalid"
render :show
end
end
def edit
#edit=User.find(params[:id])
#user=User.new
end
def update
#user=User.find(params[:id])
if #user.update_attributes(update_params)
flash[:notice]="Your data has updated successfully"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="Your data could not update..check it.."
flash[:color]="invalid"
render :edit
end
end
private
def users_params
params.require(:user).permit(:name, :email, :message,pets_attributes: [:name, :email,:message])
end
def update_params
params.require (:user).permit(:name,:email,:message,pets_attributes: [:name, :email,:message])
end
end
model/user.rb
class User < ActiveRecord::Base
has_many :pets
accepts_nested_attributes_for :pets
EMAIL_REGEX = /\A[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
validates :name, :presence => true,:length => { :minimum => 5 }
validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX
validates :message, :presence => true
end
Please help me to solve the above error.
You have space between require and (:user). Your current code is equivalent to:
def update_params
params.require(:user.permit(:name,:email,:message,pets_attributes: [:name, :email,:message]))
end
As you can see now, you call permit method on :user symbol and this is direct cause of error.
It should be:
def update_params
params.require(:user).permit(:name,:email,:message,pets_attributes: [:name, :email,:message])
end
BTW having two methods that do exactly same thing is quite pointless.
Check your question:
you have a space after require and before (:user)
Try:
def update_params
params.require(:user).permit(:name,:email,:message,
pets_attributes: [:name, :email,:message])
end
For a better way, you can have just one method:
def user_params
params.require(:user).permit(:name,:email,:message,
pets_attributes: [:name, :email,:message])
end
Instead of having separate filter methods for new and edit, you can have just one method and reuse that in both new and edit.
Just keep things Simply DRY.
I am a bit new to Ruby and am writing a program from scratch... I'm getting an error and I can't figure out where it is coming from. I've spent over an hour and i'm sure it's something stupidly simple. I have other similar pages that work fine, but there's some issue with the instance variable. It's almost an identical problem as the link provided.
Here's my error:
Showing C:/Users/kevin/Desktop/ruby_test/sites/simple_cms/app/views/sections/_form.html.erb where line #4 raised:
undefined method `collect' for nil:NilClass
Extracted source (around line #4):
1 <table summary="Section form fields">
2 <tr>
3 <th><%= f.label(:page_id, "Page") %></th>
4 <td><%= f.select(:page_id, #pages.collect {|p| [p.name, p.id]}) %>
5 </td>
6 </tr>
7 <tr>
Trace of template inclusion: app/views/sections/edit.html.erb
Rails.root: C:/Users/kevin/Desktop/ruby_test/sites/simple_cms
Here's my forms page:
<table summary="Section form fields">
<tr>
<th><%= f.label(:page_id, "Page") %></th>
<td><%= f.select(:page_id, #pages.collect {|p| [p.name, p.id]}) %>
</td>
</tr>
<tr>
<th><%= f.label(:name) %></th>
<td><%= f.text_field(:name) %></td>
</tr>
<tr>
<th><%= f.label(:position) %></th>
<td><%= f.select(:position, 1..#section_count) %></td>
</tr>
<tr>
<th><%= f.label(:visible) %></th>
<td><%= f.check_box(:visible) %></td>
</tr>
<tr>
<th><%= f.label(:content_type) %></th>
<td>
<%= f.radio_button(:content_type, 'text') %> Text
<%= f.radio_button(:content_type, 'HTML') %> HTML
</td>
</tr>
<tr>
<th><%= f.label(:content) %></th>
<td><%= f.text_area(:content, :size => '40x10') %></td>
</tr>
</table>
Here's my controller:
class SectionsController < ApplicationController
layout "admin"
def index
#sections = Section.sorted
end
def show
#section = Section.find(params[:id])
end
def new
#section = Section.new({:name => "Default"})
#pages = Page.order('position ASC')
#section_count = Section.count + 1
end
def create
#section = Section.new(section_params)
if #section.save
flash[:notice] = "Section created successfully."
redirect_to(:action => 'index')
else
#pages = Page.order('position ASC')
#section_count = Section.count
render('new')
end
end
def edit
#section = Section.find(params[:id])
end
def update
#section = Section.find(params[:id])
if #section.update_attributes(section_params)
flash[:notice] = "Section updated successfully."
redirect_to(:action => 'show', :id => #section.id)
else
#pages = Page.order('position ASC')
#section_count = Section.count
render('edit')
end
end
def delete
#section = Section.find(params[:id])
end
def destroy
section = Section.find(params[:id]).destroy
flash[:notice] = "Section destroyed successfully."
redirect_to(:action => 'index')
end
private
def section_params
params.require(:section).permit(:page_id, :name, :position, :visible, :content_type, :content)
end
end
Here's the view page (edit):
<% #page_title = "Edit Section" %>
<%= link_to("<< Back to List", {:action => 'index'}, :class => 'back-link') %>
<div class="sections edit">
<h2>Update Section</h2>
<%= form_for(:section, :url => {:action => 'update', :id => #section.id}) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<div class="form-buttons">
<%= submit_tag("Update Section") %>
</div>
<% end %>
</div>
You should define #pages and #section_count variables in appropriate controller action:
def edit
#section = Section.find(params[:id])
#pages = Page.order('position ASC')
#section_count = Section.count
end
You also have a mistake in create action. When it doesn't create a record, #section_count should be Section.count + 1 as in new action.
Your controller could be also refractor to this