I'm fairly new to rails so please bear with me.
I have a resource :examen with a has_one relation to a resource :aanwezigheidslijst.
In the aanwezigheids_controller i have everything prepared for editing "aanwezigheidslijst".
Now the problem I'm having is when editing (specificly showing whether or not a student was attending or not by checking a checkbox) each "aanwezigheidslijst" is when i submit the form it renders to 'index' (just like i want) but apparently no changes have been made to the mysql database.
There are no errors that pop up and the lay-out is like i want it, it's just the checkbox that represents the boolean "aanwezig" that isn't updated when i submit it.
The connection with the mysql database works fine with other parts of the app.
any solutions are very much appreciated.
EDIT
as proposed i took a look at the log file. I figure the Unpermitted parameters have something to do with it? can anyone clarify?
Log File:
Started PATCH "/aanwezigheidslijst/2/edit" for 127.0.0.1 at 2015-02-21 16:12:14 +0100
Processing by AanwezigheidslijstController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"uxgvXaOPs66wtYBntTr907RN4yfC0vLTfresXPURBow=", "aanwezigheidslijst"=>{"1"=>{"student"=>"Tom Nys", "aanwezig"=>"1"}, "2"=>{"student"=>"Jan de Roeck", "aanwezig"=>"1"}, "3"=>{"student"=>"Nick van Heertum", "aanwezig"=>"0"}}, "commit"=>"Save Aanwezigheidslijst", "id"=>"2"}
[1m[35mAanwezigheidslijst Load (0.0ms)[0m SELECT `aanwezigheidslijsts`.* FROM `aanwezigheidslijsts` WHERE `aanwezigheidslijsts`.`id` = 2 LIMIT 1
Unpermitted parameters: 1, 2, 3
[1m[36m (1.0ms)[0m [1mBEGIN[0m
[1m[35m (0.0ms)[0m COMMIT
Redirected to http://localhost:3000/aanwezigheidslijst/index
Completed 302 Found in 8ms (ActiveRecord: 1.0ms)
aanwezigheidslijst migration:
class CreateAanwezigheidslijsts < ActiveRecord::Migration
def change
create_table :aanwezigheidslijsts do |t|
t.string :student
t.boolean :aanwezig
t.timestamps
end
end
end
aanwezigheids_controller.rb:
class AanwezigheidslijstController < ApplicationController
def index
#aanwezigheidslijst = Aanwezigheidslijst.all
#examen = Examen.all
end
def edit
#aanwezigheidslijst = Aanwezigheidslijst.where(:examen_id => params[:id]).all
end
def update
#aanwezigheidslijst = Aanwezigheidslijst.find(params[:id])
if #aanwezigheidslijst.update(aanwezig_params)
redirect_to aanwezigheidslijst_index_path
else
render 'edit'
end
end
private
def aanwezig_params
params.require(:aanwezigheidslijst).permit(:student, :aanwezig)
end
end
edit.html.erb:
<div class="tblAanwezig">
<div class="col-xs-6 col-sm-3">
<table class="table table-bordered table-condensed" style="max-width: 300px;">
<thead>
<tr>
<th scope="col">Student</th>
<th scope="col">Aanwezig</th>
</tr>
</thead>
<%= form_tag edit_aanwezigheidslijst_url, :id => 'al_form', method: :patch do %>
<% #aanwezigheidslijst.each do |aanwezigheidslijst| %>
<%= fields_for "aanwezigheidslijst[]", aanwezigheidslijst do |al| %>
<tbody>
<tr>
<td> <%= al.text_field :student %></td>
<td><%= al.check_box :aanwezig %></td>
</tr>
</tbody>
<% end %>
<% end %>
</table>
<%= submit_tag "Save Aanwezigheidslijst" %>
<% end %>
</div>
</div>
routes.rb
Rails.application.routes.draw do
get 'aanwezigheidslijst/index'
patch 'aanwezigheidslijst/:id/edit' => 'aanwezigheidslijst#update'
get 'examen/index'
get 'comments/new'
post 'comments/new'
get 'comments/update'
get 'comments/create'
get 'application/application'
resources :comments
resources :aanwezigheidslijst
root 'comments#index'
end
Related
What I am trying to accomplish is a simple "toggle" checkbox for On/Off for a view which contains records from a model.
I have attempted to look into a "hidden" value, but it doesn't appear to work as intended.
How to get blank checkboxes to pass as false to params
When I've added: <%= hidden_field_tag "category_ids[]", '' %>
I receive Couldn't find Category with 'category_name'= when unchecking.
Essentially, the table is a Model.all, but I want to be able to modify the key value on an is_active column to true or false, depending on if the box is checked, or not. Currently, I can accomplish this for "checking" the box. But, not unchecking (passes null). I am trying accomplish this is one swoop rather than making all my checkes, and another pass for my unchecked. And, also bypassing the show/edit process. The table size is rather small, so I am not concerned with latency.
I have attempted to search as much as I could, but am at a loss. With what I've found I can do one or the other, but not both unfortunately, and I would greatly appreciate any guidance.
My view:
<h4>Categories</h4>
<%= form_tag enable_categories_path, method: :put do |f| %>
<table id="myTable" class="table table-bordered table-striped">
<tr>
<th>Enable</th>
<th>Category Name</th>
<th>Active</th>
</tr>
<tbody>
<% #categories.each do |category| %>
<tr>
<td>
<%= check_box_tag "category_ids[]", category.id, category.is_active == 1 ? 'checked' : nil %>
</td>
<td><%= link_to category.category_name, category %></td>
<td><%= category.is_active == 1 ? 'Yes' : 'No' %></td>
</tr>
<% end %>
</tbody>
</table>
<%= render 'settings/button' %>
<% end %>
Here, the checkboxes are grabbing their state from the model itself for the corresponding record, so if no action is taken on the checkbox it remains the same (or passes state back)
My controller:
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update]
def index
#categories = Category.all.order(:category_sort)
end
def show
#category = Category.find(params[:id])
end
def edit
end
def update
if #category.update(category_params)
redirect_to categories_path
else
render :edit
end
end
def enable
Category.update(params[:category_ids], params[:category_ids].map{ |e| {is_active: true} })
redirect_to categories_path
end
private
def set_category
#category = Category.find(params[:id])
end
def category_params
params[:category].permit(:id, :category_name, :is_active)
end
end
Currently, I'm only passing is_active: true, until I can figure a way to pass ALL checkbox states.
My model:
class Category < ActiveRecord::Base
self.table_name = 'categories'
has_many :metrics
end
My route:
resources :categories do
collection do
put :toggle
end
end
Everything appears to pass correctly for checked boxes. But, nothing appears in the logs for when something is unchecked.
When I've run into situations like this in Rails I usually end up using AJAX rather than mass assignment. It's actually rather easy. At least easier for me than learning the inner workings of the check_boxes and collection_check_boxes, LOL
A simple Categories table:
<table>
<thead>
<tr>
<th>Category</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<% #categories.each do |category| %>
<tr>
<td><%= category.category_name %></td>
<% status = category.is_active? ? 'Active' : 'Inactive' %>
<td id="<%= category.id %>" ><button class="button_<%= status %>"><%= link_to status, toggle_active_path(:id => category.id), :method => :post, :remote => true %></button></td>
</tr>
<% end %>
</tbody>
</table>
The lines to note are the embedded ruby setting the status variable. This is used to set the value of the class for the button. In the CSS file the button class button_Active sets the color to green and button_Inactive makes it red. It also uses this variable to set the text of the button.
Create a method in the controller that toggles the status:
def toggle_is_active
#category.toggle!(:is_active) #flips the boolean on is_active
respond_to do |format|
format.html { redirect_to(#category) }
format.js
end
Be aware that .toggle! will bypass model validations and save. If you need to ensure validations run you can use #category.toggle(:is_active).save
This will respond to format.js and call a very small file called toggle_is_active.js.erb:
$('#<%= #category.id %>').html('<%= escape_javascript(render :partial => 'toggle_active') %>');
This targets the id of the html element that we set to the id of the category in the table row.
This calls a partial called _toggle_active.html.erb and updates the appropriate <td> with the new html:
<% status = #category.is_active? ? 'Active' : 'Inactive' %>
<button class="button_<%= status %>"><%= link_to status, toggle_active_path(:id => #category.id), :method => :post, :remote => true %></button>
Now all you need is a route to access the AJAX link:
routes.rb:
post 'toggle_active' => 'categories#toggle_is_active'
Here is a working example you can clone on github. It has the stylesheets to get the look above. I think you can extrapolate this for almost any situation:
https://github.com/Beartech/category_boxes
Let's consider what's going on here:
def enable
Category.update(params[:category_ids], params[:category_ids].map{ |e| {is_active: true} })
redirect_to categories_path
end
Can you post what params[:category_ids] looks like here? the map here doesn't quite make sense. Also, what is the data type of is_active in the database?
I am trying to perform a database search in an application, however, I have been unable to get the search to work properly.
In the index page I have the option to search or display all items in the database, however the return all always seems to be called, instead of the search. If someone searches, I would like to only display the searched for item when the search is completed.
I am, however, running into some issues.
articles_controller.rb:
class ArticlesController < ApplicationController
def index
if params[:id]
fun = Article.find_by(title: params[:id].search)
else
#articles = Article.all
end
end
def show
#article = Article.find(params[:search])
end
def new
#article = Article.new
end
def edit
#article = Article.find(params[:id])
end
def create
#article = Article.new(params.require(:article).permit(:title, :text))
if #article.save
redirect_to #article
else
render 'new'
end
end
def update
#article = Article.find(params[:id])
if #article.update(article_params)
redirect_to #article
else
render 'edit'
end
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
article.rb:
class Article < ActiveRecord::Base
validates :title, presence: true,
length: { minimum: 5 }
def self.search(search)
if :search
Article.where('tite LIKE ?', "%#{search}%")
else
Article.all
end
end
end
index.html.erb:
<h1>Listing articles</h1>
<%= link_to 'New article', new_article_path %>
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th colspan="3"></th>
</tr>
<% #articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
<%= form_tag articles_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :title => nil %>
</p>
<% end %>
</table>
Backend DB:
Started GET "/articles?search=asdfa&commit=Search&utf8=%E2%9C%93" for ::1 at 2016-03-14 15:01:12 -0400
Processing by ArticlesController#index as HTML
Parameters: {"search"=>"asdfa", "commit"=>"Search", "utf8"=>"✓"}
Article Load (0.1ms) SELECT "articles".* FROM "articles"
Rendered articles/index.html.erb within layouts/application (1.4ms)
Completed 200 OK in 19ms (Views: 18.6ms | ActiveRecord: 0.1ms)
The latest error/incorrect call is:
Started GET "/assets/application.self-3b8dabdc891efe46b9a144b400ad69e37d7e5876bdc39dee783419a69d7ca819.js?body=1" for ::1 at 2016-03-14 15:39:25 -0400
Started GET "/articles?search=asdfa&commit=Search&utf8=%E2%9C%93" for ::1 at 2016-03-14 15:39:40 -0400
Processing by ArticlesController#index as HTML
Parameters: {"search"=>"asdfa", "commit"=>"Search", "utf8"=>"✓"}
Article Load (0.1ms) SELECT "articles".* FROM "articles"
Rendered articles/index.html.erb within layouts/application (1.3ms)
Completed 200 OK in 18ms (Views: 17.2ms | ActiveRecord: 0.1ms)
What exactly am I doing wrong? How can I fix/make this work?
You've defined search method in your model, but you are not using in it in your controller:
def index
#articles = Article.search params[:search]
end
In your model, you have some logic errors (symbol :search instead of search variable, tite instead of title ):
def self.search search
search.present? ? where('title LIKE ?', "%#{search}%") : all
end
In your controller you have:
def index
if params[:id]
fun = Article.find_by(title: params[:id].search)
else
#articles = Article.all
end
end
but you are definitely not passing any id to the controller via the form.
For example, you can change the condition to:
if params[:search]
and then find by:
Article.find_by(title: params[:search])
currently im accessing my join table directly. the reason im doing this is because i only want the staff to be able to adjust the status
im facing problem with
undefined method order_task_path' for #<#<Class:0x00000009bf62c0>:0x0000000a6d7c70>`
with parameter Parameters:
{"id"=>"1,1"}
i'm able to display the join table according to my need. the problem is when i try to display it in edit.
here is my ordertask controller
class OrdersTasksController < ApplicationController
before_action :set_status, only: [:show]
def index
#orders = Order.all
##status = OrderTask.includes(:task,:order).where(order_id: params[:id])
end
def edit
#status = OrderTask.find(params[:id])
end
def show
end
def update
respond_to do |format|
if #status.update(order_params)
format.html { redirect_to #status, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: #order }
else
format.html { render :edit }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_status
#status = OrderTask.includes(:task).where(order_id: params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order_task,:order).permit(:id,:order_id,:status)
end
end
my show.html.erb
<p id="notice"><%= notice %></p>
<table class="table table-hover">
<tr>
<td><h4>Order Number : <%= #status.first.order.order_number %></h4>
</td>
</tr>
<tr>
<td>Task
</td>
<td>Status:
</td>
</tr>
<tr>
<% #status.each do |i| %>
<td><%= i.task.task_name %>
</td>
<td><%= i.status %>
</td>
<td><%= link_to 'Edit', edit_orders_task_path(i) %></td>
</tr>
<% end %>
</table>
<%= link_to 'Back', orders_tasks_path %>
my _form.html.erb
<%= form_for(#status) do |f| %>
<% if #status.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#status.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% #status.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<table class="table table-hover">
<tr>
<td><%= f.label "List of task" %>
</td>
<td><%= f.label "Status" %>
</td>
</tr>
<tr>
<td><%= f.task_id %>
</td>
<td><div class="dropdown">
<%= f.select(:status,['In progress', 'Completed'], {}, {class: "control"})%> </div>
</td>
</tr>
<tr>
<td>
</td>
<td><%= f.submit %>
</td>
</tr>
</table>
<% end %>
and my routes
resources :orders
resources :services
resources :tasks
resources :customers
resources :staffs
resources :orders_tasks
root 'staffs#index'
and lastly my ordertask model
class OrderTask < ActiveRecord::Base
self.primary_key = [:order_id,:task_id]
self.table_name = "Orders_tasks"
belongs_to :order
belongs_to :task
end
hope u guys can give suggestion or something to help me with this. thx in advance.
EDIT
here is my route.rb
C:\Users\Idea\DHMS>rake routes
Prefix Verb URI Pattern Controller#Action
orders GET /orders(.:format) orders#index
POST /orders(.:format) orders#create
new_order GET /orders/new(.:format) orders#new
edit_order GET /orders/:id/edit(.:format) orders#edit
order GET /orders/:id(.:format) orders#show
PATCH /orders/:id(.:format) orders#update
PUT /orders/:id(.:format) orders#update
DELETE /orders/:id(.:format) orders#destroy
services GET /services(.:format) services#index
POST /services(.:format) services#create
new_service GET /services/new(.:format) services#new
edit_service GET /services/:id/edit(.:format) services#edit
service GET /services/:id(.:format) services#show
PATCH /services/:id(.:format) services#update
PUT /services/:id(.:format) services#update
DELETE /services/:id(.:format) services#destroy
tasks GET /tasks(.:format) tasks#index
POST /tasks(.:format) tasks#create
new_task GET /tasks/new(.:format) tasks#new
edit_task GET /tasks/:id/edit(.:format) tasks#edit
task GET /tasks/:id(.:format) tasks#show
PATCH /tasks/:id(.:format) tasks#update
PUT /tasks/:id(.:format) tasks#update
DELETE /tasks/:id(.:format) tasks#destroy
customers GET /customers(.:format) customers#index
POST /customers(.:format) customers#create
new_customer GET /customers/new(.:format) customers#new
edit_customer GET /customers/:id/edit(.:format) customers#edit
customer GET /customers/:id(.:format) customers#show
PATCH /customers/:id(.:format) customers#update
PUT /customers/:id(.:format) customers#update
DELETE /customers/:id(.:format) customers#destroy
staffs GET /staffs(.:format) staffs#index
POST /staffs(.:format) staffs#create
new_staff GET /staffs/new(.:format) staffs#new
edit_staff GET /staffs/:id/edit(.:format) staffs#edit
staff GET /staffs/:id(.:format) staffs#show
PATCH /staffs/:id(.:format) staffs#update
PUT /staffs/:id(.:format) staffs#update
DELETE /staffs/:id(.:format) staffs#destroy
orders_tasks GET /orders_tasks(.:format) orders_tasks#index
POST /orders_tasks(.:format) orders_tasks#create
new_orders_task GET /orders_tasks/new(.:format) orders_tasks#new
edit_orders_task GET /orders_tasks/:id/edit(.:format) orders_tasks#edit
orders_task GET /orders_tasks/:id(.:format) orders_tasks#show
PATCH /orders_tasks/:id(.:format) orders_tasks#update
PUT /orders_tasks/:id(.:format) orders_tasks#update
DELETE /orders_tasks/:id(.:format) orders_tasks#destroy
root GET / staffs#index
According to the error message undefined method order_task_path' for #<#<Class:0x00000009bf62c0>:0x0000000a6d7c70>, the url helper method does not exist.
you can rake rake routes in the terminal to get all the routes and route helpers.
resources :orders do
resources :tasks
end
generate the following routes and helpers.
order_tasks GET /orders/:order_id/tasks(.:format) tasks#index
POST /orders/:order_id/tasks(.:format) tasks#create
new_order_task GET /orders/:order_id/tasks/new(.:format) tasks#new
edit_order_task GET /orders/:order_id/tasks/:id/edit(.:format) tasks#edit
order_task GET /orders/:order_id/tasks/:id(.:format) tasks#show
PATCH /orders/:order_id/tasks/:id(.:format) tasks#update
PUT /orders/:order_id/tasks/:id(.:format) tasks#update
DELETE /orders/:order_id/tasks/:id(.:format) tasks#destroy
resources :orders do
resources :orders_tasks
end
generate the following routes and helpers.
order_orders_tasks GET /orders/:order_id/orders_tasks(.:format) orders_tasks#index
POST /orders/:order_id/orders_tasks(.:format) orders_tasks#create
new_order_orders_task GET /orders/:order_id/orders_tasks/new(.:format) orders_tasks#new
edit_order_orders_task GET /orders/:order_id/orders_tasks/:id/edit(.:format) orders_tasks#edit
order_orders_task GET /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#show
PATCH /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#update
PUT /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#update
DELETE /orders/:order_id/orders_tasks/:id(.:format) orders_tasks#destroy
http://guides.rubyonrails.org/routing.html#nested-resources
I'm writing an Recipe app in Rails. Now I'm stuck in this error. I spent a week to find the solution for this problem.
Update model
Here is my model:
class Recipe < ActiveRecord::Base
has_many :ingredient_recipes
has_many :ingredients, :through => :ingredient_recipes
accepts_nested_attributes_for :ingredient_recipes
end
class Ingredient < ActiveRecord::Base
has_many :ingredient_recipes
has_many :recipes, :through => :ingredient_recipes
end
class IngredientRecipe < ActiveRecord::Base
belongs_to :recipe
belongs_to :ingredient
end
IngredientRecipe is a join model that is used to store the value of recipe and ingredient.
In 'New' action, I want to create new recipe along with the Ingredient for that recipe, and specify the quantity (quantity is an additional attribute in the join table IngredientRecipe) for that ingredient.
When I click submit, it just creates a new Recipe, it doesn't create a record in the Join table.
Here is my error:
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"AbnDeDLDWq3lvy4pozvXStVy7NeOIUuv1DU1U2/2EJ6n
/jM6E1669hyB90733XTY9DGAvc2hbbDmbL6NwhqCUg==",
"recipe"=>{"rec_name"=>"j", "rec_description"=>"k",
"ingredient_recipe"=>{"ingredient"=>{"id"=>"1"},
"quantity"=>"1"}}, "commit"=>"Create Recipe"}
Unpermitted parameter: ingredient_recipe
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `recipes` (`rec_name`, `rec_description`,
`created_at`, `updated_at`) VALUES ('j', 'k', '2015-06-25 21:48:09', '2015-06-25 21:48:09')
(1.1ms) COMMIT
Redirected to http://localhost:3000/recipes/50
Completed 302 Found in 6ms (ActiveRecord: 1.4ms)
Updated controller
My recipe controller: Updated controller
def new
#recipe = Recipe.new
3.times { #recipe.ingredient_recipes.build.build_ingredient }
end
def create
#recipe = Recipe.new(recipe_params)
respond_to do |format|
if #recipe.save
format.html { redirect_to #recipe, notice: 'Recipe was successfully created.' }
format.json { render :show, status: :created, location: #recipe }
else
format.html { render :new }
format.json { render json: #recipe.errors, status: :unprocessable_entity }
end
end
end
My recipe view form:
<%= form_for(#recipe) do |f| %>
<% if #recipe.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#recipe.errors.count, "error") %> prohibited this recipe from being saved:</h2>
<ul>
<% #recipe.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :rec_name %><br>
<%= f.text_field :rec_name %>
</div>
<div class="field">
<%= f.label :rec_description %><br>
<%= f.text_area :rec_description %>
</div>
<table>
<thead>
<tr>
<th>Ingredients</th>
<th>Unit</th>
<th>Quantity</th>
<th>New Quantity</th>
</tr>
</thead>
<tbody>
<%= f.fields_for :ingredient_recipes do |fi| %>
<%= fi.fields_for do |i| %>
<tr>
<td> <%=i.collection_select(:ingredient_id, Ingredient.all, :id, :ing_name) %></td>
<% end %>
<td> <%=fi.text_field :quantity %></td>
</tr>
<% end %>
</tbody>
</table>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
No errors after I updated but here is the parameters what I get when I submit create action:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"NCT4NgS6ZvbqpcS4+CsoYI4pJurYzwsCyj5U6k3MTwSFqDpdLMX+XVFIpAP/pXD3ZDNr6T6mIOf58gUk6SEqOQ==", "recipe"=>{"rec_name"=>"s", "rec_description"=>"s", "ingredient_recipes_attributes"=>{"0"=>{"ingredient_id"=>"2", "quantity"=>"1"}, "1"=>{"ingredient_id"=>"1", "quantity"=>"1"}, "2"=>{"ingredient_id"=>"3", "quantity"=>"1"}}}, "commit"=>"Create Recipe"}
(0.6ms) BEGIN
SQL (4.6ms) INSERT INTO recipes (created_at, updated_at) VALUES ('2015-07-01 00:37:28', '2015-07-01 00:37:28')
(2.1ms) COMMIT
Redirected to http://localhost:3000/recipes/65
Completed 302 Found in 24ms (ActiveRecord: 7.3ms)
Started GET "/recipes/65" for 127.0.0.1 at 2015-06-30 17:37:28 -0700
Processing by RecipesController#show as HTML
Parameters: {"id"=>"65"}
Recipe Load (4.7ms) SELECT recipes.* FROM recipes WHERE recipes.id = 65 LIMIT 1
Rendered recipes/show.html.erb within layouts/application (0.7ms)
Completed 200 OK in 136ms (Views: 126.4ms | ActiveRecord: 4.7ms)
It seems everything is on the right way but I don't know why after render show action It doesn't show the attributes of the recipe I just added, and It also didn't create the record in the join table.
Please help me! Thanks so much
You have an error in your model:
class Ingredient < ActiveRecord::Base
has_many :ingredient_recipes, inverse_of: :ingredient_recipes, autosave: true
has_many :recipes, :through => :ingredient_recipes
The following line is not correct. An inverse relationship to itself is not valid:
has_many :ingredient_recipes, inverse_of: :ingredient_recipes, autosave: true
This is why you're getting the error:
Unpermitted parameter: ingredient_recipe
Next steps (Added)
Remove the incorrect inverse_of relationship from the ingredient model
Evaluate whether you need an inverse_of relationship and what it should do
Only you know what your app needs to do, but if you need the original inverse_of ingredient_recipes, it should be here:
class IngredientRecipe < ActiveRecord::Base
belongs_to :recipe, :inverse_of ingredient_recipes
belongs_to :ingredient
accepts_nested_attributes_for :ingredient
end
More debug advice: Remove "autosave" and create child record explicitly (Edit)
You must first create the parent record successfully before adding the "belongs to" child. Your autosave a parameter supposedly does this action, but it is not working for some reason, which you have to debug. To do this I suggest that you explicitly create an action on the child tables after you create your parent recipe record.
Once you get the parent and child records creating properly with explicit calls, then put the autosave back in the model, rollback the explicit creates and see if the parent save invokes the child save. I always use explicit saves because I want to control the process.
This app consists of a form to submit and currently I am trying to print a few rows of a table. This is working, but unfortunately I am also getting a single long string of the entire database table attributes. There is nothing in the code that I have written (I believe) which would cause this. I fear that this is some unseen rails magic, any insight would be great!
The controller:
class StudentsController < ApplicationController
def new
#student = Student.new
end
def create
student_map = {"student_id" => params[:student_id], "student_name" => params[:student_name],
"major" => params[:major], "minor" => params[:minor], "other_information" => params[:other_information],
"class_year_id" => params[:class_year_id], "hours_st" => params[:hours], "qr_id" => qr_id,}
if (newStudentRow.save)
redirect_to action: 'index'
else
render action: 'new'
end
end
def index
#students = Student.all
end
end
The Index view:
<h1>Students#index</h1>
<p>Find me in app/views/students/index.html.erb</p>
<table>
<thead>
<tr>
<th>Student Name</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<%= #students.each do |s| %>
<tr>
<td><%= s.student_name %></td>
<td><%= s.student_id %></td>
</tr>
</tbody>
<% end %>
</table>
After entering data and submitting the form, this link shows the following output:
Thanks for the help!
Change:
<%= #students.each do |s| %>
To this:
<% #students.each do |s| %>
In Ruby, each executes the block for each element AND returns the array. Having the = outputs the array, which is why you are seeing that long string.