I've spent a while trying to debug this behavior unsuccessfully, so I'm hoping for help figuring out why my nested resource parameters appear to be getting included in the URL in the wrong order. For some reason, adding and deleting lessons for a course works, but editing a lesson crashes because ActiveRecord tries to find a lesson using the course ID and vice versa.
Course and lesson models
class Course < ApplicationRecord
has_many :lessons, dependent: :destroy
extend FriendlyId
friendly_id :title, use: :slugged
class Lesson < ApplicationRecord
belongs_to :course
extend FriendlyId
friendly_id :title, use: :slugged
Lessons controller
class LessonsController < ApplicationController
before_action :set_lesson, only: [:show, :edit, :update, :destroy ]
def index
#lessons = Lesson.all
end
def show
end
def new
#lesson = Lesson.new
#course = Course.friendly.find(params[:course_id])
authorize #lesson
end
def edit
authorize #lesson
end
def create
#lesson = Lesson.new(lesson_params)
#course = Course.friendly.find(params[:course_id])
#lesson.course_id = #course.id
if #lesson.save
redirect_to course_lesson_path(#course, #lesson), notice: "Lesson was successfully created."
else
render :new, status: :unprocessable_entity
end
end
def update
authorize #lesson
if #lesson.update(lesson_params)
redirect_to course_lesson_path(#course, #lesson), notice: "Lesson was successfully updated."
else
render :edit
end
end
def destroy
authorize #lesson
#lesson.destroy
redirect_to course_path(#course), notice: "Lesson was successfully destroyed."
end
private
def set_lesson
#course = Course.friendly.find(params[:course_id])
#lesson = Lesson.friendly.find(params[:id])
end
def lesson_params
params.require(:lesson).permit(:title, :content, :course_id)
end
end
Routes
resources :courses do
resources :lessons
end
And what shows up when I do rails routes:
edit_course_lesson GET /courses/:course_id/lessons/:id/edit(.:format)
However, when I actually edit a lesson, the parameters seem to get switched, which causes a crash. See below for an example of where it thinks the fourth lesson is the course.
URL: /courses/fourth-lesson/lessons/forensic-science-344/edit
ActiveRecord::RecordNotFound in LessonsController#edit
can't find record with friendly id: "fourth-lesson"
private
def set_lesson
#course = Course.friendly.find(params[:course_id]) <- Crashes on this line
#lesson = Lesson.friendly.find(params[:id])
end
Update: here's the form for editing a lesson.
.container
= simple_form_for([#course, #lesson]) do |f|
= f.error_notification
= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?
.form-inputs
= f.input :title
= f.input :content
%small
= f.error :content, class: 'text-danger'
.form-actions
= f.button :submit, class: 'btn btn-primary my-4'
It turns out that I didn't pass in the course parameter on the edit link. I had link_to 'Edit', edit_course_lesson_path(lesson).
It should have been edit_course_lesson_path(#course, lesson).
Thanks for everyone's patience, and many thanks to Deepesh for finally getting it into my head to look at the edit link.
Related
this is the case:
models/product.rb
belongs_to :brand
models/brand.rb
has_many :products
controllers/products_controller.rb
class ProductsController < ApplicationController
def new
#product = Product.new
#brands = Brand.all
end
def create
#product = Product.new(params[:product])
if #product.save
redirect_to :show
else
render :new, format: :html
end
end
end
On product create the user can add a brand name and if the user add a brand name on next time to create a product the form for the brand did not show again.
Someone please have a idea how to do something like that on rails?
That's something to add in your view.
Use a condition around your brand form :
form #product do |f|
f.text_field :name
if not #product.new_record?
f.select_field :brand_id, #brands, :id
end
end
I have someone of a unique problem. I have 3 tables in the database that I need to populate with data. All tables are in relation to each other. The first table's info will be static and populated from a hash. The second table is the table that is usually targeted with data.
I am having a tough time trying to add data into the second table using strong parameters. I get an error param is missing or the value is empty: entries
Modles:
client.rb
class Client < ActiveRecord::Base
has_many :entries
end
Entry.rb
class Entry < ActiveRecord::Base
belongs_to :client_name
has_many :extra_data
end
extra_data.rb
class ExtraData < ActiveRecord::Base
belongs_to :entries
end
class ClientsController < ApplicationController
before_action :set_client, only: [:show, :update, :destroy, :edit]
# submit for all intended purposes.
#
def new
#entries = Entry.new()
end
def create
#client = Client.new(CLEINT_ATTR)
if #client.save
#entries = Entry.new(submit_params)
redirect_to action: :index
else
flash.alert "you failed at life for today."
redirect_to action: :index
end
end
.
.
.
private
def submit_params
params.require(:entries).permit( :full_name,:email,:opt_in )
end
def set_client
#client = Client.find(params[:id])
end
end
form
<%= simple_form_for(:client, url: {:controller => 'clients', :action => 'create'}) do |f| %>
<%= f.input :full_name %>
<%= f.input :email %>
<%= f.input :opt_in %>
<%= f.button :submit, class: "btn-primary" %>
<% end %>
Routes:
Rails.application.routes.draw do
resources :clients do
resources :entries do
resources :extra_data
end
end
root 'clients#index'
end
In the Database Client data goes in with out a problem. I am having a problem getting the data from the form itself.
This answer is the culmination of a few different parts.
I figured out I was not saving any data into the model. So I needed to make another if statement.
def create
#client = Client.new(CLEINT_ATTR)
if #client.save
#entries = Entry.new(submit_params)
if #entries.save
flash[:alert] = "Failure! everything is working."
redirect_to action: :index
else
flash[:alert] = "Success! at failing."
end
else
flash[:alert] = "you failed at life for today."
redirect_to action: :thanks
end
end
Also changing the form from :entries Helped. I also had a typo in my permit statment. I had :opt_in when I needed to use :optin Thanks #tmc
I am trying to follow this video railscast #364 but I am having a lot of trouble with my nested routes. When I use this code:
<%= link_to "up", vote_movie_review_path(#movie, #reviews, type: "up"), method: "post" %>
I get this error when I select up vote:
ActiveRecord::RecordNotFound in ReviewsController#vote
Couldn't find Review with 'id'=# <Review::ActiveRecord_Relation:0x007f0358c1e550>
This is my route:
vote_movie_review POST /movies/:movie_id/reviews/:id/vote(.:format) genre_linkers#vote
I created another model that was not nested using this code:
<%= link_to "up", vote_movie_path(movie, type: "up"), method: "post" %>
and that one worked. So I am thinking it has to be something wrong with my path or how I am calling the objects. I have spent almost all day working on this, I really need help.
review_controller.rb
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
before_action :set_movie
before_action :authenticate_user!
respond_to :html
def index
#reviews = Review.all
respond_with(#reviews)
end
def show
end
def vote
value = params[:type] == "up" ? 1 : -1
#review = Review.find(params[:id])
#review.add_evaluation(:vote, value, current_user)
redirect_to :back, notice: "thanks for the vote"
end
def new
#review = Review.new
respond_with(#review)
end
def edit
end
def create
#review = Review.new(review_params)
#review.user_id = current_user.id
#review.movie_id = #movie.id
if #review.save
redirect_to #movie
else
render 'new'
end
end
def update
#review.update(review_params)
respond_with(#review)
end
def destroy
#review.destroy
respond_with(#review)
end
private
def set_review
#review = Review.find(params[:id])
end
def set_movie
#movie = Movie.find(params[:movie_id])
end
def review_params
params.require(:review).permit(:genre, :description, :vote)
end
end
routes.rb
Rails.application.routes.draw do
devise_for :users
resources :movies do
resources :reviews do
member { post :vote }
end
end
root 'movies#index'
end
and the model
review.rb
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :movie
has_reputation :votes, source: :user, aggregated_by: :sum
end
The culprit is this part of your link_to: vote_movie_review_path(#movie, #reviews, type: "up"). #reviews is an ActiveRecord::Relation and not a Review record, hence no record with an ID can be found.
I have two models Hotel and Address.
Relationships are:
class Hotel
belongs_to :user
has_one :address
accepts_nested_attributes_for :address
and
class Address
belongs_to :hotel
And I need to save in hotels table and in addresses table from one form.
The input form is simple:
<%= form_for(#hotel) do |f| %>
<%= f.text_field :title %>
......other hotel fields......
<%= f.fields_for :address do |o| %>
<%= o.text_field :country %>
......other address fields......
<% end %>
<% end %>
Hotels controller:
class HotelsController < ApplicationController
def new
#hotel = Hotel.new
end
def create
#hotel = current_user.hotels.build(hotel_params)
address = #hotel.address.build
if #hotel.save
flash[:success] = "Hotel created!"
redirect_to #hotel
else
render 'new'
end
end
But this code doesn't work.
ADD 1
Hotel_params:
private
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price)
end
ADD 2
The main problem is I don't know how to render form properly. This ^^^ form doesn't even include adress fields (country, city etc.). But if in the line
<%= f.fields_for :address do |o| %>
I change :address to :hotel, I get address fields in the form, but of course nothing saves in :address table in this case. I don't understand the principle of saving in 2 tables from 1 form, I'm VERY sorry, I'm new to Rails...
You are using wrong method for appending your child with the parent.And also it is has_one relation,so you should use build_model not model.build.Your new and create methods should be like this
class HotelsController < ApplicationController
def new
#hotel = Hotel.new
#hotel.build_address #here
end
def create
#hotel = current_user.hotels.build(hotel_params)
if #hotel.save
flash[:success] = "Hotel created!"
redirect_to #hotel
else
render 'new'
end
end
Update
Your hotel_params method should look like this
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price,address_attributes: [:country,:state,:city,:street])
end
You should not build address again
class HotelsController < ApplicationController
def new
#hotel = Hotel.new
end
def create
#hotel = current_user.hotels.build(hotel_params)
# address = #hotel.address.build
# the previous line should not be used
if #hotel.save
flash[:success] = "Hotel created!"
redirect_to #hotel
else
render 'new'
end
end
Bottom line here is you need to use the f.fields_for method correctly.
--
Controller
There are several things you need to do to get the method to work. Firstly, you need to build the associated object, then you need to be able to pass the data in the right way to your model:
#app/models/hotel.rb
Class Hotel < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
#app/controllers/hotels_controller.rb
Class HotelsController < ApplicationController
def new
#hotel = Hotel.new
#hotel.build_address #-> build_singular for singular assoc. plural.build for plural
end
def create
#hotel = Hotel.new(hotel_params)
#hotel.save
end
private
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price, address_attributes: [:each, :address, :attribute])
end
end
This should work for you.
--
Form
Some tips for your form - if you're loading the form & not seeing the f.fields_for block showing, it basically means you've not set your ActiveRecord Model correctly (in the new action)
What I've written above (which is very similar to that written by Pavan) should get it working for you
I have three models: Lesson, Situation, Fate(join table).
In this app, A situation can have many lessons and a lesson can belong to multiple situations.
I would essentially like the tables to look like this.
Situation
id.....name.....................description
1.....Ordering Food......You go into a restaurant and order food.
2.....Introduce yourself.You meet someone for the first time and you introduce yourself.
Lesson
id.....name............description..............lesson_text
1......Order food....How to order food..Blah blah blah, this is how you order food.
2......Call the waiter.How to call the waiter Blah blah blah, this is how you call the waiter
3 Pay for food How to pay for food Blah blah blah, this is how you pay for food.
4 Greet a person How to greet a person Blah blah blah, this is how you greet a person.
5 Ask a question How to ask a question Blah blah blah, this is how you ask a question.
Fate
situation_id lesson_id required
1.................1...............yes
1.................2...............yes
1.................3...............no
2.................3...............yes
2.................4...............yes
2.................5...............yes
I have the tables set up but I'm not sure how I would associate a lesson to a situation.
This is what my application looks like currently
Situations controller
class SituationsController < ApplicationController
def index
#situations = Situation.all
end
def new
#situation = Situation.new
end
def create
#situation = Situation.new(params[:situation])
respond_to do |format|
if #situation.save
format.html { redirect_to #situation }
end
end
end
def show
#situation = Situation.find(params[:id])
#lesson = #situation.lessons.new
end
def edit
#situation = Situation.find(params[:id])
end
def update
#situation = Situation.find(params[:id])
respond_to do |format|
if #situation.update_attributes(params[:situation])
format.html { redirect_to #situation }
end
end
end
def destroy
#situation = Situation.find(params[:id])
#situation.destroy
respond_to do |format|
format.html { redirect_to situations_path }
end
end
end
Lessons controller
class LessonsController < ApplicationController
def index
#lessons = Lesson.all
end
def new
#lesson = Lesson.new
end
def create
#lesson = Lesson.new(params[:lesson])
respond_to do |format|
if #lesson.save
format.html { redirect_to #lesson }
end
end
end
def show
#lesson = Lesson.find(params[:id])
end
def edit
#lesson = Lesson.find(params[:id])
end
def update
#lesson = Lesson.find(params[:id])
respond_to do |format|
if #lesson.update_attributes(params[:lesson])
format.html { redirect_to #lesson }
end
end
end
def destroy
#lesson = Lesson.find(params[:id])
#lesson.destroy
respond_to do |format|
format.html { redirect_to lessons_path }
end
end
end
Routes
root :to => 'situations#index'
resources :situations do
resources :lessons
end
resources :difficulties
Situation.rb
class Situation < ActiveRecord::Base
attr_accessible :name, :description
has_many :fates
has_many :lessons, :through => :fates
end
Lesson.rb
class Lesson < ActiveRecord::Base
attr_accessible :name, :description, :difficulty_id, :lesson_text
has_many :fates
has_many :situations, :through => :fates
end
Fate.rb
class Fate < ActiveRecord::Base
belongs_to :lesson
belongs_to :situation
end
Thanks for the help! and I'm really sorry about the messy formatting.
So if you are creating a new situation and want to also create new lessons that will be associated with it..
app/models/situation.rb
attr_accessible :name, :description, :difficulty_id, :lesson_text, :lessons_attributes
accepts_nested_attributes_for :lessons
app/controllers/situations_controller.rb
def new
#situation = Situation.new
2.times do{#situation.lessons.build}
respond_to do |format|
format.html
end
end
app/views/lessons/_form.html.erb
<% form_for #situation do |f| %>
<%= f.text_field :name %>
<%= f.text_field :description %>
<% f.fields_for :situations do |lesson_field| %>
<%= lesson_field.text_field :name %>
<%= lesson_field.text_field :lesson_text %>
<% end %>
<%= f.submit %>
<% end %>
Essentially you need a nested form (there is plenty examples). I typed this off the iPhone, hope it works )