Ruby on Rails controller syntax - ruby-on-rails

I am new to Rails, and just working my way through my first solo project, but I seem to be running into a syntax error with a constant not being initialized (Ive gotten several of these, but each seems to have a different cause.....not quite sure how i keep getting the same error with different causes :)):
uninitialized constant DatastringsController::Datastrings
DatastringsController:
class DatastringsController < ApplicationController
def new
end
def create
#datastrings = Datastrings.new(datastrings_params) #ERROR returned on this line
#datastrings.save
redirect_to #datastrings
end
def show
#datastrings = Datastrings.find(params[:id])
end
private
def datastrings_params
params.require(:datastrings).permit(:title, :text)
end
end
I believe my form is correct:
<%= form_for :datastrings, url: datastrings_path do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>

The main problem you have is here:
<%= form_for :datastrings, url: datastrings_path do |f| %>
form_for really should be populated with an ActiveRecord object, as this allows Rails to build the relative paths it requires correctly.
Although I don't know why this is the case, your current setup is basically trying to render DatastringsController::Datastrings -- primarily because you've not set up your form_for correctly
--
Fix
If you want to create a datastring object, I'd follow convention and do this:
#config/routes.rb
resources :datastrings
#app/controllers/datastrings_controller.rb
Class DatastringsController < ApplicationController
def new
#datastring = Datastring.new
end
def create
#datastring = Datastring.new(datastring_params)
#datastring.save
end
private
def datastring_params
params.require(:datastring).permit(:title, :text)
end
end
#app/views/datastrings/new.html.erb
<%= form_for #datastring do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
--
YOU ALSO NEED TO NAME YOUR MODELS IN SINGULAR
Looking at it now, it seems that your main issue is likely that you've named your model as a plural.
The reason this will be bad is that when you load Rails, it will load all your models, and consequently, allow you to call them by referencing their class name. If a model is plural, I don't think it will load it correctly, causing the error you've highlighted
If you name your model to the following, it should be better:
#app/models/datastring.rb
Class Datastring < ActiveRecord::Base
end

Related

ActionController::ParameterMissing: param is missing or the value is empty:

so i know that there´s a lot of questions like that, but none had answered my questions and solved my problem. So, I am with this problem for about a week and I can´t solve it! I am really new to ruby on rails, but i´ve tried tried everything. I have this (ActionController::ParameterMissing:
param is missing or the value is empty:opinion) and I don´t know how to fix it. There´s all the code (I am newbie so it is really simple) :
Opinion Controller :
class OpinionsController < ApplicationController
def new
#opinion = Opinion.new
end
def create
#opinion = Opinion.new(opi_params)
#opinion.save
redirect_to #opinion
end
def show
#opinion = Opinion.find(params[:id])
end
private
def opi_params
params.require(:opinion).permit(:body)
end
end
New :
<h1>Opinions</h1>
<%= form_for :opinion do |f| %>
<%= f.label :body %><br>
<%= f.text_field :body %><br>
<br>
<%= f.submit "Create an option" %>
<% end %>
DB :
class CreateOpinions < ActiveRecord::Migration
def change
create_table :opinions do |t|
t.string :body
end
end
end
Show :
<h1>Your Opinions:</h1>
<div>
<%= #opinion.body %>
</div>
PLEASE HELP ME! I am getting crazy because i cannot solve it! Thanks :)
<h1>Opinions</h1>
<%= form_for #opinion do |f| %>
<%= f.label :body %><br>
<%= f.text_field :body %><br>
<br>
<%= f.submit "Create an option" %>
<% end %>
Change :opinion to the instance variable #opinion.
This issue may also occur when the form is submitted with the field body empty if it is your case change the strong parameters to
params.fetch(:opinion, {}).permit(:body)
I recommend dropping a debugger like pry or byebug right between def create and #opinion = Opinion.new(opi_params) and seeing what params is coming in. You might be missing opinion, which will trigger the ParameterMissing error.
Also, are you getting this error through the browser or through your test? If you are getting this error from your test, it might be your set up.
In the meantime, try params.permit(:body) in your opi_params method.

form_for Ruby On Rails

I'm trying to follow a tutorial on using basic AJAX to add a record to a list in place, and I'm having issues using form form_for.
Here is my code.
<%= form_for ([#product, #product.new]) do |p| %>
<p>
<%= p.label :product_part %>
<%= p.text_field :product_part%>
</p>
<p>
<%= p.submit %>
</p>
<% end %>
The error I am getting is
undefined method `new' for nil:NilClass
I understand why I am getting the error (#products hasn't been "initialized") but I have no idea how to fix this issue (I am sure it's simple). I have seen something about putting a resource in the routes file, but I do not know for sure.
If you're trying to make a form for a new product, you should (in your controller) be setting #product to an instance of a new Product:
# app/controllers/products_controller.rb
def new
#product = Product.new
end
In your view, using [#product, #product.new] makes no sense. You can't invoke new on an instance of a product. It's very unclear why you're not simply using the following, which is the correct use of form_for with a new instance of an ActiveRecord model:
form_for #product do |p|
Do this:
#app/controllers/products_controller.rb
class ProductsController < ApplicationController
def new
#product = Product.new
render :form
end
def edit
#product = Product.find params[:id]
render :form
end
end
#app/views/products/form.html.erb
<%= form_for #product, remote: true do |f| %>
<%= p.label :product_part %>
<%= p.text_field :product_part%>
<%= f.submit %>
<% end %>
This will do everything you need for both the new and edit methods (which you raised concerns about in your comments with #meagar).
This should be corroborated with the following routes (you can see why here):
#config/routes.rb
resources :products
I would say In case you need to look the form_for helper ; to understand the behavior of the method.
The method form_for It accept the argument as record, options = {}. The value of record could be a symbol object or a newly object of respective class in your case Person.new.
Second argument could be
:url, :namespace, :method, :authenticity_token, :remote , :enforce_utf8, :html
Among them :remote => true option is used as the Ajaxify your request.
form_for is a helper that assists with writing forms. form_for takes a :remote option. It works like this:
<%= form_for(#article, remote: true) do |f| %>
....
<% end %>
This will generate the following HTML:
<form accept-charset="UTF-8" action="/articles" class="new_article" data-remote="true" id="new_article" method="post">
...
</form>
Note the data-remote="true". Now, the form will be submitted by Ajax rather than by the browser's normal submit mechanism.
For more info about Form-For helper
Hope this solve your problem!!!.

Rails Undefined method

I already know there is a lot of undefined method questions, But I can't see whats wrong with mine so I need some help!
heres my form that i have
<% title("Home Page") %>
<h1><i class="fa fa-home"></i> Add Event <small>views/pages/home.html.erb</small></h1>
<div class="row">
<%= simple_form_for Newevent.new do |f| %>
<%= f.input :eventname, required: true %>
<%= f.input :eventdesc %>
<%= f.input :eventdate %>
<%= f.input :eventimage %>
<div class="col s6">
<%= f.input :stubhublink %>
<%= f.input :seatwavelink %>
<%= f.input :viagogolink %>
</div>
<%= f.button :submit %>
<% end %>
</div>
I also have this in the controller
def create
create_params = params[:newevent].permit(:eventname, :eventdesc, :eventdate, :eventimage, :viagogolink, :seatwavelink, :stubhublink)
#newevent = Newevent.new(create_params)
byebug
#newevent.save!
end
and this in the model
class Newevent < ActiveRecord::Base
def params
params.require(:newevent).permit(:eventname, :eventdesc, :eventdate, :eventimage, :viagogolink, :seatwavelink, :stubhublink )
end
end
It was working fine with 3 (which were eventname, eventdate and eventimage) however after adding the other 4 in it now doesn't work. Any ideas?
Sorry heres the error!
NoMethodError in Newevents#new
Showing /Users/samroberts/Desktop/admitme/app/views/newevents/new.html.erb where line #6 raised:
undefined method `eventdesc` for #<Newevent:0x007fcaeee41f68>
Sam
Several problems here buddy:
1. eventdesc Missing
The simple explanation for your error is that your eventdesc attribute is missing from your NewEvent model's table.
Since we don't have your table - or migrations - to observe, I'll have to give you a simple test:
<%= simple_form_for Newevent.new do |f| %>
<%= f.input :eventname, required: true %>
<%= f.input :eventdesc %> #-> remove this line
...
Remove that, refresh the page and see if it works. If the error persists, it may mean another attribute is missing. If it disappears, it means this attribute is missing from your db, and as such you should use rails g migration to create a new one:
$ rails g migration AddEventDesc
#db/migrate/add_event_desc_xxxxxxxx.rb
class AddEventDesc
def change
add_column :new_events, :eventdesc, :string
end
end
2. Params
Part of Rails 4's infrastructure is to use strong params to pass data from your controller to model.
As such, you need the following syntax:
#app/controllers/new_events_controller.rb
class NewEventsController < ApplicationController
def new
#newevent = NewEvent.new
end
def create
#newevent = NewEvent.new new_event_params
#newevent.save
end
private
def new_event_params #-> you can call this whatever you like
params.require(:newevent).permit(:eventname, :eventdesc, :eventdate, :eventimage, :viagogolink, :seatwavelink, :stubhublink )
end
end
You need to keep your strong params function in your controller, not your model.
3. Model Name
Finally, this won't do much for you directly, but in the long run will help you massively; your model name.
Your model is NewEvent.
If this is what you want to call it, that is good. However, I have found the best way forward with model names is to keep them simple, preferably to one word.
I'd strongly recommend calling your model Event, so you can call #event = Event.new etc -- it just flows better.

Getting an 'undefined method' error when trying to generate simple_form

I'm just trying to get some practice in with rails and have started my first project. I am creating a simple project where personal trainers can register profiles and look for work at gyms.
However when trying to navigate to the new personal trainer page this error pops up:
undefined method `pts_path' for #<#<Class:0x5d14ef8>:0x5690b68>
My personal trainer controller looks like this:
class PersonaltrainersController < ApplicationController
def index
#PT = Pt.all
end
def new
#PT = Pt.new
end
def show
end
def create
end
def contact
end
def edit
end
end
Under the routes file I have:
Rails.application.routes.draw do
resources :personaltrainers
root 'personaltrainers#index'
end
My simple_form looks like:
<%= simple_form_for #PT do |form| %>
<%= form.input :name %>
<%= form.input :age %>
<%= form.input :sex %>
<%= form.input :experience %>
<% end %>
personaltrainers_path GET /personaltrainers(.:format) personaltrainers#index
POST /personaltrainers(.:format) personaltrainers#create
new_personaltrainer_path GET /personaltrainers/new(.:format) personaltrainers#new
edit_personaltrainer_path GET /personaltrainers/:id/edit(.:format) personaltrainers#edit
personaltrainer_path GET /personaltrainers/:id(.:format) personaltrainers#show
PATCH /personaltrainers/:id(.:format) personaltrainers#update
PUT /personaltrainers/:id(.:format) personaltrainers#update
DELETE /personaltrainers/:id(.:format) personaltrainers#destroy
root_path GET / personaltrainers#index
Any help would be greatly appreciated.
Change your form code to:
<%= simple_form_for #PT, url: personaltrainers_path do |form| %>
<%= form.input :name %>
<%= form.input :age %>
<%= form.input :sex %>
<%= form.input :experience %>
<% end %>
undefined method pts_path' raised when simple_form_for trying to make a url from the model(pts it is a pluralized form of the pt model), but your routes have another resource name personaltrainers. All that you need, it's pass explicit url to the form helper, in this case it should be personaltrainers_path according your routes file.
You index and new method should be:
def index
#PT = Personaltrainer.all
end
def new
#PT = Personaltrainer.new
end
Btw, we (ruby devs) have a convention to use small case variable names, underscore in case of more_than_one_word. We use ALL_CAPS for constants.

Ruby on rails unitialized constant

I am very new at Ruby on Rails, and I am not quite sure what this error means:
uninitialized constant StorevaluesController
I have a storevalue_controller.rb which works (I can get to content on the page) but when I try to submit a form like this:
new.html.erb
<h1>Fill out form to add to db</h1>
<%= form_for :storevalue, url: storevalue_path do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
rails throws the error I reference above.
storevalue_controller.rb
class StorevalueController < ApplicationController
def new
end
def create
#storevalue = Storevalue.new(storevalue_params)
#storevalue.save
redirect_to #storevalue
end
def show
#storevalue = Storevalue.find(params[:id])
end
private
def storevalue_params
params.require(:storevalue).permit(:title, :text)
end
end
my route trace:
welcome_index_path GET /welcome/index(.:format) welcome#index
root_path GET / welcome#index
storevalue_new_path GET /storevalue/new(.:format) storevalue#new
storevalue_path POST /storevalue(.:format) storevalues#create
new_storevalue_path GET /storevalue/new(.:format) storevalues#new
edit_storevalue_path GET /storevalue/edit(.:format) storevalues#edit
GET /storevalue(.:format) storevalues#show
PATCH /storevalue(.:format) storevalues#update
PUT /storevalue(.:format) storevalues#update
DELETE /storevalue(.:format) storevalues#destroy
Note the error is plural "values" and your actual controller name is not. You're using the plural name somewhere when it doesn't exist. In Ruby, class names are constants. Hence you have the error message wording, which I agree is pretty misleading at face value.

Resources