in nested form- Can't mass-assign protected attributes: - ruby-on-rails

I have read through several threads and nothing so far. I am trying to nest one form in another. I am getting the can't mass assign protected attributes error. \
app/controllers/projects_controller.rb:46:in new'
app/controllers/projects_controller.rb:46:increate'
Projects_controller.rb
def create
#project = Project.new(params[:project])
respond_to do |format|
if #project.save
format.html { redirect_to #project, notice: 'Project was successfully created.' }
format.json { render json: #project, status: :created, location: #project }
else
format.html { render action: "new" }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
project.rb
WF::Application.routes.draw do
resources :line_items
resources :projects do
resources :line_items
end
devise_for :users
get 'about' => 'pages#about'
get 'Production' => 'projects#index'
root :to => 'pages#home'
end
here is the error...
ActiveModel::MassAssignmentSecurity::Error in ProjectsController#create
Can't mass-assign protected attributes: line_item
here is my project model
class Project < ActiveRecord::Base
attr_accessible :quantity
# may be unnessary
attr_accessible :line_items_attributes
belongs_to :user
has_many :line_items
accepts_nested_attributes_for :line_items, :allow_destroy => true
end

Assuming you're trying to create line items through your project model, you'll need to make sure you have the following lines in your Project model:
# project.rb
Class Project < ActiveRecord::Base
attr_accessible :line_items_attributes
accepts_nested_attributes_for :line_items
...
end

Rails is trying to protect you from accidentally assigning values you don't mean to.
You can tell Rails what values are ok to assign in this way:
attr_accessible :value1, :value2
If you add that line to the top of the Project model (replace :value1 and :value2 with the actual names of your columns), it should allow you to do what you're attempting.
For more info, here's the docs.

Related

How to pass id from different table in rails?

Using Devise Gem to store user.
Created One to Many association between User to Project.
Created One to Many Association Between User and Site and Then One to Many Association between Project and Site.
But the error is i am not able to Assign project_id to Site from User Creation form. i am able to Assign from console. here is my code-
sites_controller.rb
def create
#site = current_user.sites.build(site_params)
respond_to do |format|
if #site.save
format.html { redirect_to #site, notice: 'Transactions was successfully Uploaded.' }
format.json { render :show, status: :created, location: #site }
else
format.html { render :new }
format.json { render json: #site.errors, status: :unprocessable_entity }
end
end
end
def site_params
params.require(:site).permit(:name, :amount)
end
site.rb(model)
belongs_to :user
belongs_to :project
User.rb
has_many :projects
has_many :sites
project.rb
has_many :sites, dependent: :destroy
How can i pass project_id on site creation. Is there any other simple way to resolve such problem?
Based on the comments in the question:
# project_id needs to be available to the method,
# in order to be added to site.
#
# Either pass it through params or get it from database
# based on your business logic.
site_params = site_params.merge({project_id: project_id})
#site = current_user.sites.build(site_params)
Should help.
Try permitting the foreign key as well.
def site_params
params.require(:site).permit(:name, :amount, :project_id)
end

rails : association tabel (has_and_belongs_to_many) not save any record

i use rails 5 , simple form. in my app there is a Category model and there is a OnlineProduct model. i dont know why when i want to add some categories to my OnlineProduct association table remain empty and don't change.
Category model:
class Category < ApplicationRecord
has_ancestry
has_and_belongs_to_many :internet_products
end
InternetProduct model:
class InternetProduct < ApplicationRecord
belongs_to :user
belongs_to :business
has_and_belongs_to_many :categories
end
InternetProduct controller:
def new
#internet_product = InternetProduct.new
end
def create
#internet_product = InternetProduct.new(internet_product_params)
respond_to do |format|
if #internet_product.save
format.html { redirect_to #internet_product, notice: 'Internet product was successfully created.' }
format.json { render :show, status: :created, location: #internet_product }
else
format.html { render :new }
format.json { render json: #internet_product.errors, status: :unprocessable_entity }
end
end
end
private:
def internet_product_params
params.require(:internet_product).permit(:name, :description, :mainpic, :terms_of_use,
:real_price, :price_discount, :percent_discount,
:start_date, :expire_date, :couponـlimitation, :slung,
:title, :meta_data, :meta_keyword, :enability, :status,
:like, :free_delivery, :garanty, :waranty, :money_back,
:user_id, :business_id,
categoriesـattributes: [:id, :title])
end
and in the view only the part of who relate to categories :
<%= f.association :categories %>
all the categories list in view (form) but when i select some of them not save in database. in rails console i do this
p = InternetProduct.find(5)
p.categories = Category.find(1,2,3)
this save to database without any problem, what should i do ?
tanks for reading this
I found solution to solve this. when we use has_and_belong_to_many or any other relation , if you want to use collection select in simple_form , in the model also should be add this command for nesting form
accepts_nested_attributes_for :categories
also in the controller in related method for example in the new we should
def new
#internet_product = InternetProduct.new
#internet_product.categories.build
end

Rails - routes - weird errors

I am making a rails 4 app.
I just created a scaffold for Universities.
The universities table has three attributes, being :name, :logo, :post_code.
I created three universities as a test. They come up in the console.
The university.rb model has these associations:
The university model has these associations:
has_many :faculties
has_many :students
has_many :academics#, through: :researchers
has_many :educators
has_many :faculties
has_many :courses, through: :faculties
has_many :programs#, through: :academics
has_many :alumnus
has_one :policy_ip
has_one :policy_publication
has_one :policy_commerciality
has_many :eaip_assets
has_many :commercial_ip_assets
has_many :community_activities
has_many :ip_transfer_successes
has_many :spin_outs
has_many :ip_asset_managers#, through: :universities
has_many :expression_of_interest_options#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_assignments#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_licensings#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_collaborations#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_spin_outs#, through: :ip_asset_manager, -> { where submitted: true }
has_many :awards
has_many :profiles
The view university#show has:
<div class="col-md-7 col-md-offset-1">
<div class="profilet"><%= #university.name %></div>
<%= link_to 'Edit', edit_university_path(#university) %> |
<%= link_to 'Back', universities_path %>
The first error I get (on each of my 3 records) is:
undefined method `name' for nil:NilClass
When I change the line so that it is on:
<div class="profilet"><%= #university.try(:name) %></div>
I get an error on the 'edit' link that says:
No route matches {:action=>"edit", :controller=>"universities", :id=>nil} missing required keys: [:id]
When I delete the edit link and try again, I get a blank page with a 'back' link.
I can't understand whats going wrong. My console shows I definitely have 3 records in the university table (each with an id 1, 2 or 3). My routes are resources - (as they are with all of my other models) and this is the first problem I've encountered with the edit link.
I have strong params in my universities controller for each of the three attributes in the table, so I"m stuck for things to try to do to fix this.
Any ideas?
The universities controller has:
class UniversitiesController < ApplicationController
# before_action :set_university, only: [:show, :edit, :update, :destroy]
# GET /universities
# GET /universities.json
def index
#universities = University.all
end
# GET /universities/1
# GET /universities/1.json
def show
end
# GET /universities/new
def new
#university = University.new
end
# GET /universities/1/edit
def edit
end
# POST /universities
# POST /universities.json
def create
#university = University.new(university_params)
respond_to do |format|
if #university.save
format.html { redirect_to #university, notice: 'University was successfully created.' }
format.json { render action: 'show', status: :created, location: #university }
else
format.html { render action: 'new' }
format.json { render json: #university.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /universities/1
# PATCH/PUT /universities/1.json
def update
respond_to do |format|
if #university.update(university_params)
format.html { redirect_to #university, notice: 'University was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #university.errors, status: :unprocessable_entity }
end
end
end
# DELETE /universities/1
# DELETE /universities/1.json
def destroy
#university.destroy
respond_to do |format|
format.html { redirect_to universities_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_university
#university = University.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def university_params
params[:university].permit(:name, :logo, :post_code)
end
end
It means you didn't have object university in the actions. You have to enable the line below:
before_action :set_university, only: [:show, :edit, :update, :destroy]
The associated instance variable #university is nil therefore the route helper could not generate a route for it.
Please check your controller's edit action and fix the problem there.
You have #university with the id=nil, if you want to use edit url helper you need to provide #university entity with the id. In other words you can edit record that exists in DB, otherwise you should create new.
Wow you have a lot of problems here.
undefined method `name' for nil:NilClass
This means one of your variables is not initialized. The cause of this is where the fun begins.
When you define <%= #university.x %>, you're calling a method on your #university variable. If that variable is not populated with any data, or is undefined, Ruby automatically assigns the NilClass class to it.
You mention you're seeing this error when referencing the #university variable. This means either in your routes or controller, it's not being populated.
Here's how to fix it:
#config/routes.rb
resources :universities #-> url.com/universities/:id
#app/controllers/universities_controller.rb
class UniversitiesController < ApplicationController
before_action :set_university, only: [:show, :edit, :update, :destroy]
def index
#universities = University.all
end
def edit
end
def show
end
end
This should give you the capacity to use the following:
#app/views/universities/show.html.erb
<% if #university %>
<%= #university.name %>
<% end %>

Has And Belongs to Many Through Save and Update

Here are my models:
class Examination < ActiveRecord::Base
has_many :categorizations
has_many :exam_statuses, :through => :categorizations
end
class Categorization < ActiveRecord::Base
belongs_to :examination
belongs_to :exam_status
end
class ExamStatus < ActiveRecord::Base
has_many :categorizations
has_many :examinations, :through => :categorizations
end
I can assign relations from the console without any problem by typing;
e = Examination.first
e.exam_status_ids = [1,2]
And also in the examinations/index.html.erb file I can list exam_statuses without any problem.
The problem is, I can't update or create any exam_status relations from examinations/_form.html.erb file!
I'm trying to make this with simple_form:
<%= f.association :exam_statuses, as: :check_boxes, label: 'Sınavın Durumu' %>
Its listing all the statuses with checkboxes but not updating them.
Logs saying:
"Unpermitted parameters: exam_status_ids"
And finally my controller, which is generated by "scaffold" by default, for update is:
def update
respond_to do |format|
if #examination.update(examination_params)
format.html { redirect_to #examination, notice: 'Examination was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #examination.errors, status: :unprocessable_entity }
end
end
end
From what your logs say, you should permit the parameter, in the controller:
def examination_params
params.require(:examination).permit(:exam_status_ids)
end
Don't forget to add other parameters in the permit call!
Then you can use it in your controller's action:
def update
...
#examination.update_attributes! examination_params
...
end
I think you need to use accepts_nested_attributes in this case to get it updated.
For more details you can refer this article

Add current_user Devise to Mongoid relations

Hi Guys I have a Relationships in Mongoid and I can not add current_user to this relation for get the user that create the deal. A relation with 3 model.
I have three models user.rb, house.rb and deal.rb
user.rb Relationships (devise model)
# Relationships
has_many :houses, dependent: :destroy
has_many :deals, dependent: :destroy
key :title
house.rb
# Relationships
belongs_to :user
embeds_many :deals
deal.rb
# Relationships
embedded_in :house, :inverse_of => :deals
belongs_to :user
In my routes.rb
resources :houses do
resources :deals
end
In my houses_controller.rb in my create method I get current_user for each house of this side:
def create
##house = House.new(params[:house])
#house = current_user.houses.new(params[:house])
respond_to do |format|
if #house.save
format.html { redirect_to #house, notice: 'House was successfully created.' }
format.json { render json: #house, status: :created, location: #house }
else
format.html { render action: "new" }
format.json { render json: #house.errors, status: :unprocessable_entity }
end
end
end
In my deals_controller.rb I have the created method this:
def create
#house = House.find_by_slug(params[:house_id])
#user = User.find(:user_id)
#deal = #house.deals.create!(params[:deal])
redirect_to #house, :notice => "Comment created!"
end
How I can add to this last method create, the current_user that created the deal?
You can simply add these two lines to the create action:
#deal.user=current_user
#deal.save
And I would also suggest you not to use create! instead you should use .new and .save like in the scaffolded create actions! ;)

Resources