Rails nested attributes are not saving - ruby-on-rails

I am new to rails and am learning to complete an Inventory System database project for school.
Here is my Item model:
class Item < ActiveRecord::Base
self.primary_key ='item_id'
validates :item_id, :presence => true
has_one :vendor_item, :dependent => :destroy
has_one :vendor, :through => :vendor_item
accepts_nested_attributes_for :vendor_item
end
Here is my item controller:
class ItemsController < ApplicationController
def new
#item = Item.new
#all_vendors = Vendor.all
#item_vendor = #item.build_vendor_item
end
def create
#item = Item.new(item_params)
vendor = params[:vendors][:id]
#item_vendor = #item.build_vendor_item(:vendor_id => vendor)
#item_vendor.save
#raise params.inspect
if #item.save
redirect_to #item
else
render 'new'
end
end
def show
#item = Item.find(params[:id])
#item_vendor = #item.vendor_item
end
def index
#items = Item.all
end
def priceUnder500
#priceUnder500 = Item.where("price < ?", 500)
respond_to do |format|
format.html
format.js
end
end
def priceOver500
#priceOver500 = Item.where("price > ?", 500)
respond_to do |format|
format.html
format.js
end
end
def edit
#item = Item.find(params[:id])
#all_vendors = Vendor.all
#vendor_item = #item.vendor_item
end
def update
#item = Item.find(params[:id])
vendor = params[:vendors][:id]
if #item.vendor_item.blank?
#item.build_vendor_item(:vendor_id => vendor)
end
if #item.update(params[:item].permit(:item_id, :name, :category, :description, :reorder_level, :quantity, :price, :vendor_item_attributes => [:vendor_item_id]))
redirect_to items_path
else
render 'edit'
end
end
def destroy
#item = Item.find(params[:id])
#item.destroy
redirect_to items_path
end
private
def item_params
params.require(:item).permit(:item_id, :name, :category, :description, :reorder_level, :quantity, :price, :vendor_item_attributes => [:vendor_item_id])
end
end
And my _form partial for items:
<%= form_for #item do |f| %>
<% if #item.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#item.errors.count, "error") %> prohibited
this post from being saved:</h2>
<ul>
<% #item.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :item_id, 'Item Id' %><br>
<%= f.text_field :item_id %>
</p>
<%= fields_for #item_vendor do |vii| %>
<div class= "vendorItemId">
<%= vii.label :vendor_item_id%>
<%= vii.text_field :vendor_item_id%><br>
</div>
<% end %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :category %><br>
<%= f.text_field :category %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.label :reorder_level %><br>
<%= f.text_field :reorder_level %>
</p>
<p>
<%= f.label :quantity %><br>
<%= f.text_field :quantity %>
</p>
<p>
<%= f.label :price %><br>
<%= f.text_field :price %>
</p>
<h3>Vendors:</h3>
<%= fields_for(#item_vendor) do |ab| %>
<div class= "field">
<%= ab.label "All Vendors:" %><br>
<%= collection_select(:vendors, :id, #all_vendors, :id, :name, {},{:multiple => false})%>
</div>
<% end %>
<p>
<%= f.submit %>
</p>
<% end %>
vendor_item contains a reference to item_id, vendor_id, and has another attribute of vendor_item_id. When the program saves, item_id and vendor_id save but vendor_item_id does not save. I have tried every online source but cannot seem to get that one attribute to save. I am using rails 4. Thanks in advance for any help provided.

You haven't saving the result in an instance variable in create action.
Try giving like this in your create action.
def create
#item = Item.new(item_params)
vendor = params[:vendors][:id]
#item_vendor = #item.build_vendor_item(:vendor_id => vendor)
if #item.save
redirect_to #item
else
render 'new'
end
end

def create
#item = Item.new(item_params)
#vendor = params["item"]["vendors"]
if #item.save
#item.create_vendor_item(#vendor.id => vendor).save
redirect_to #item
else
render 'new'
end
end

Related

ForbiddenAttributesError in Rails 5

I am getting Forbidden Attributes Error even though I have used strong parameters in Rails. I have two models: Posts and Categories.
Here is my Post Controller:
class PostsController < ApplicationController
def index
#posts=Post.all
end
def new
#post=Post.new
#category=Category.all
end
def create
#post = Post.new(params[:post])
if #post.save
redirect_to posts_path,:notice=>"Post saved"
else
render "new"
end
end
def allowed_params
params.require(:post).permit(:title, :body, :category_id)
end
end
And here is my view for posts/new:
<%= form_for #post do |f| %>
<p>
<%= f.label :title %></br>
<%= f.text_field :title%><br/>
</p>
<p>
<%= f.label :body %></br>
<%= f.text_area :body%><br/>
</p>
<p>
<%= f.select :category_id, Category.all.collect{|x| [x.name,x.id]},{:include_blank =>"Select one"}%><br/>
</p>
<p>
<%= f.submit "Add Post" %>
</p>
<% end %>
But I am still getting Error.
You need to use allowed_params instead of params[:post]:
#post = Post.new(allowed_params)

Rails passing params to different model and then saving it not working

I have a 'post' controller in that I have two variable title and body which I am passing through strong parameters.But I need to use two other variable which are path and name which are in different model name 'Document'..And also I am saving the content in database ..but unable to do so..getting this error view [posts/_form.html.erb]
undefined method `name' for #
[posts_controller]
class PostsController < ApplicationController
before_action :authenticate_user!
def index
#posts = Post.user_post(current_user).order('created_at DESC').paginate(:page => params[:page], :per_page => 5)
end
def new
#post = Post.new
end
def show
#post = find_params
end
def create
#post = Post.create(post_params)
#post.user = current_user
if #post.save
redirect_to #post
else
render 'new'
end
end
def edit
#post = find_params
end
def update
#post = find_params
if #post.update(post_params)
redirect_to #post
else
render 'edit'
end
end
def destroy
#post = find_params
#post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
Document.new(params,:files=>[])
end
def find_params
Post.find(params[:id])
end
end
[post/_form.html.erb]
<%= form_for #post,html: { multipart: true } do |f| %>
<% if #post.errors.any? %>
<div id="errors">
<h2><%= pluralize(#post.errors.count, "error") %> prevented this post from saving:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_field :body %><br>
<br>
<%= f.label :name %> <br>
<%= f.text_field :name %><br>
<br>
<br>
<%= f.label :path %><br>
<%= f.file_field :path %><br>
<%= f.submit %>
<% end %>
[document.rb]
class Document < ActiveRecord::Base
validates :name, presence: true
validates :path, presence: true
validates :resource_type, presence: true
validates :resource_id, presence: true
mount_uploader :path, PathUploader
validates :name, presence: true
# def self.abc
# params.permit(:name,:path)
# end
def initialize(params,file)
params=file[:name]
#params.permit(name =>:name,path =>:path)
end
end
undefined method `name' for #
You're referencing a non-existent attributes for your Post form:
<%= form_for #post,html: { multipart: true } do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_field :body %><br>
<%= f.submit %>
<% end %>
Remove :name & :path references.
--
If you want to pass "extra" attributes to another model, you need to use accepts_nested_attributes_for or set the params separately to your "primary" model:
#app/models/post.rb
class Post < ActiveRecord::Base
has_many :documents
accepts_nested_attributes_for :documents
end
#app/models/document.rb
class Document < ActiveRecord::Base
belongs_to :post
end
This will allow you to pass the documents as "nested" attributes of your Post model:
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
#post = Post.new
#post.documents.build
end
def create
#post = Post.new post_params
#post.save
end
private
def post_params
params.require(:post).permit(:title, :body, documents_attributes: [:name, :path])
end
end
#app/views/posts/_form.html.erb
<%= form_for #post do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<%= f.fields_for :documents do |d| %>
<%= d.text_field :name %>
<%= d.text_field :path %>
<% end %>
<%= f.submit %>
<% end %>
So undefined method on a model will indicate that, well, the method doesn't exist on the model. Want to see a model's methods? Post.methods. However, in this example, the column name is not defined on the model., and you're trying to tell Post that it has a name. What you need to do is nest your parameters.
While there is a ton of cleaning up that might want to focus on first, your answer is found in the accepts_nestable_attributes_for class methods, as shown here, http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html, and strong_params documentation as shown here, http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
In your case, you want to create a new document from a post. Your permitted params hash will look like this,
params.require(:post).permit(:title, :body, :document_attributes => [:name])
Ensure that document_attributes is singular; if a person has_many pets (for example), then you'd have pets_attributes.
In your form, something that often trips people up is the builder.
<%= form_for #post do |f| %>
<%= f.text_field :title %>
<%= f.text_field :body %>
<%= f.fields_for #post.document do |document_field| %>
<%= document_field.text_field :name %>
<% end %>
<%= f.submit %>
<% end %>
Make sure that you're telling ERB that <%= f.fields_for %>, not just <% f.fields_for %>.

Rails 4 - select_tag does not pass id for field

I cannot pass the lecture_id to the created object:
Basically it should create the project with the lecture_id based on the dropdown menu. It does not seem to pass the data.
If for instance I add <%= f.input :lecture_id %> it will pass the data
<%= simple_form_for(#project) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= select_tag(:lecture_id, options_for_select(#lecture_options)) %>
<%= f.input :company_name %>
<%= f.input :phone_number %>
<%= f.input :body %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Controller:
def new
#lecture_options = Lecture.all.map{|u| [u.title, u.id]}
#project = Project.new
respond_to do |format|
format.html
format.js
end
authorize #project
end
def create
#project = current_user.projects.build(project_params)
if #project.save
flash[:success] = "You have successfully created a project."
redirect_to profile_path(current_user)
else
render action: 'new'
end
authorize #project
end
def project_params
params.require(:project).permit(:company_name, :phone_number, :body, :user_id, :title, :lecture_id)
end
Models:
Lecture.rb
has_many :projects
Project.rb
class Project < ActiveRecord::Base
belongs_to :user
belongs_to :lecture
end
You should change select_tag to :
<%= select_tag("project[lecture_id]", options_for_select(#lecture_options)) %>

param is missing or the value is empty: answer

I'm new to ruby on rails and I'm not understanding what exactly I'm doing wrong. I have a form for submitting a question for a multiple choice trivia game the question is supposed to be saved to a question database table and the 4 answers saved to an answer table with the question_id as a foreign key. However whenever I click the submit button with valid data entered for all fields, I keep getting the error, "param is missing or the value is empty: answer" from this block of code in my questions controller:
def answer_params
params.require(:answer).permit({:question_id => [#question.id]},:answer_text, :correct)
end
Here is the full class for my questions_controller.rb:
class QuestionsController < ApplicationController
def new
#question = Question.new
#answer1 = Answer.new
#answer2 = Answer.new
#answer3 = Answer.new
#answer4 = Answer.new
end
def create
#question = Question.new(question_params)
if #question.save
#answer1 = Answer.new(answer_params)
#answer2 = Answer.new(answer_params)
#answer3 = Answer.new(answer_params)
#answer4 = Answer.new(answer_params)
if #answer1.save && #answer2.save && #answer3.save && #answer4.save
redirect_to root_path
end
else
render 'new'
end
end
private
def question_params
params.require(:question).permit(:username, :question)
end
def answer_params
params.require(:answer).permit({:question_id => [#question.id]}, :answer_text, :correct)
end
end
answers_controller.rb:
class AnswersController < ApplicationController
def new
#answer = Answer.new(answer_params)
end
def create
#question = Question.find(params[:id])
#answer = Answer.new(answer_params)
if #answer.save
redirect_to root_path
end
end
private
def answer_params
params.require(:answer).permit({:question_id => [#question.id]}, :answer_text, :correct)
end
end
new.html.erb:
<%= form_for(#question) do |f| %>
<%= f.hidden_field :username, :value => current_user.email %>
<br>
<%= f.label :category %>
<%= f.text_field :category %>
<br>
<%= f.label :question %>
<%= f.text_field :question %>
<br>
<%= f.fields_for(#answer1) do |c| %>
<%= c.label :correct_answer %>
<%= c.text_field :answer_text %>
<%= c.hidden_field :correct, :value => true %>
<br>
<% end %>
<%= f.fields_for(#answer2) do |i| %>
<%= i.label :incorrect_answer1 %>
<%= i.text_field :answer_text %>
<%= i.hidden_field :correct, :value => false %>
<br>
<% end %>
<%= f.fields_for(#answer3) do |j| %>
<%= j.label :incorrect_answer2 %>
<%= j.text_field :answer_text %>
<%= j.hidden_field :correct, :value => false %>
<br>
<% end %>
<%= f.fields_for(#answer4) do |k| %>
<%= k.label :incorrect_answer3 %>
<%= k.text_field :answer_text %>
<%= k.hidden_field :correct, :value => false %>
<% end %>
<br>
<%= f.submit "Submit my question", class: "btn btn-primary"%>
<% end %>
question.rb:
class Question < ActiveRecord::Base
belongs_to :category
has_many :answers
end
answer.rb:
class Answer < ActiveRecord::Base
belongs_to :question
end
Can anyone tell me where I'm going wrong?

undefined method `model_name' for NilClass:Class : error while editing simple form

I am trying to add a basic form for product creation.
I am able to crate new product and show product but when I try to edit a product I face "undefined method `model_name' for NilClass:Class "error
Here is my PrdouctControllerClass: (controllers/products_controller.rb)
class ProductsController < ApplicationController
def index
#products = Product.order("name")
#products =Product.new
#products =Product.all
end
def show
#product = Product.find(params[:id])
end
def new
#product = Product.new
end
def create
#product = Product.new(product_params)
if #product.save
redirect_to #product, notice: "Successfully created product."
else
render :new
end
end
private
def product_params
params.require(:product).permit(:name, :price, :category, :ratings)
end
end
def edit
#product = Product.find (params[:id])
end
private
def id_params
params.require(:product).permit(:name, :price, :ratings, :category)
end
def update
#product = Product.find(params[:product])
redirect_to #product, notice: " Successfully updated product"
else
render :edit
end
def destroy
#products = Product.find (params[:id])
#product.destroy
redirect_to products_url, notice: "successfully destroyed products"
end
**and here is the form (App/Views/products/_form.html.erb**)
<%= simple_form_for(#product) do |f| %>
<% if #product.errors.any?%>
<div class="error_messages">
<h2><%= pluralize(#product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% #product.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :price %><br />
<%= f.text_field :price %>
</div>
<div class="field">
<%= f.label :released_on %><br />
<%= f.date_select :released_on %>
</div>
<div class="field">
<%= f.check_box :discontinued %>
<%= f.label :discontinued %>
</div>
<div class="field">
<%= f.label :rating %><br />
<%= f.radio_button :rating, 1 %> 1
<%= f.radio_button :rating, 2 %> 2
<%= f.radio_button :rating, 3 %> 3
<%= f.radio_button :rating, 4 %> 4
<%= f.radio_button :rating, 5 %> 5
</div>
<div class="field">
<%= hidden_field_tag "product[category_ids][]", nil %>
<% Category.all.each do |category| %>
<%= check_box_tag "product[category_ids][]", category.id, #product.category_ids.include?(category.id), id: dom_id(category) %>
<%= label_tag dom_id(category), category.name %><br />
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and here is the error message I am getting:
_app_views_products__form_html_erb__1297814100543601928_70242432121140
app/views/products/_form.html.erb, line 1
undefined method `model_name' for NilClass:Class
I tried to search Google/Stafkoverflow but I didn't find any question related to this problem.
Thanks in advance for any help
Make your controller to look like:-
class ProductsController < ApplicationController
def index
#products = Product.order("name")
#product =Product.new
##products =Product.all
end
def show
#product = Product.find(params[:id])
end
def new
#product = Product.new
end
def create
#product = Product.new(product_params)
if #product.save
redirect_to #product, notice: "Successfully created product."
else
render :new
end
end
def edit
#product = Product.find (params[:id])
end
def update
#product = Product.find(params[:id])
if #product.update(product_params)
redirect_to #product, notice: " Successfully updated product"
else
render :edit
end
end
def destroy
#products = Product.find (params[:id])
#product.destroy
redirect_to products_url, notice: "successfully destroyed products"
end
private
def product_params
params.require(:product).permit(:name, :price, :ratings, :category_ids => [])
end
end

Resources