I've spent a few hours trying to solve this problem in a Rails 5 project that I have. The issue is that I keep getting:
Unpermitted parameters: :item_instance_ids, :note_ids
when I submit a form. I believe that the relationships between the models are wrong. I'm using a polymorphic relationship which is the first time I've used it. I've looked through so many posts on StackOverFlow as well as guides on the web but nothing seems to help me.
Basically, I have an incoming purchases form - like an ordering form and within that form you should be able to add multiple items, like a laptop, keyboard, monitor, to the order => the item instances model.
Anyways, here is my code:
incoming_purchases.rb:
class IncomingPurchase < ApplicationRecord
# Relations
has_many :item_instance, :as => :instance_wrapper
has_many :notes, :as => :notable
belongs_to :user
end
item_instance.rb
class ItemInstance < ApplicationRecord
# Relations
belongs_to :instance_wrapper, polymorphic: true
belongs_to :item
belongs_to :user
has_many :notes, :as => :notable
end
views/incoming_purchases/_form.html.erb:
<%= simple_form_for(#incoming_purchase) do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="form-inputs">
<%= f.association :item_instance, as: :check_boxes, :label_method => lambda { |item_instance| "#{item_instance.item.description}" } %>
<%= f.label(:date_ordered, "Order Date:") %>
<%= f.text_field(:date_ordered, class: 'form-control-date') %>
<%= f.association :user, :label_method => lambda { |user| "#{user.username}" } %>
<%= f.input :order_number %>
<%= f.input :vendor %>
<%= f.input :po_number %>
<%= f.input :tax %>
<%= f.input :shipping %>
<%= f.association :notes %>
</div>
<div class="form-actions">
<%= f.button :submit, class: "btn btn-outline-success" %>
</div>
<% end %>
incoming_puchases_controller.rb:
class IncomingPurchasesController < ApplicationController
before_action :set_incoming_purchase, only: [:show, :edit, :update, :destroy]
def new
#incoming_purchase = IncomingPurchase.new
end
def create
puts '*********************'
puts params
puts '*********************'
puts incoming_purchase_params
puts '**********************'
#incoming_purchase = IncomingPurchase.new(incoming_purchase_params)
respond_to do |format|
if #incoming_purchase.save
format.html { redirect_to #incoming_purchase, notice: 'Incoming purchase was successfully created.' }
format.json { render :show, status: :created, location: #incoming_purchase }
else
format.html { render :new }
format.json { render json: #incoming_purchase.errors, status: :unprocessable_entity }
end
end
end
private
def set_incoming_purchase
#incoming_purchase = IncomingPurchase.find(params[:id])
end
def incoming_purchase_params
params.require(:incoming_purchase).permit(:item_instances_id, :date_ordered, :user_id, :order_number, :vendor, :po_number, :tax, :shipping, :notes_id)
end
end
schema.rb:
ActiveRecord::Schema.define(version: 2020_08_31_200026) do
create_table "incoming_purchases", options: "ENGINE=InnoDB DEFAULT CHARSET=latin1", force: :cascade do |t|
t.bigint "item_instances_id"
t.date "date_ordered"
t.bigint "user_id"
t.string "order_number"
t.string "vendor"
t.integer "po_number"
t.decimal "tax", precision: 8, scale: 2
t.decimal "shipping", precision: 8, scale: 2
t.bigint "notes_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["item_instances_id"], name: "index_incoming_purchases_on_item_instances_id"
t.index ["notes_id"], name: "index_incoming_purchases_on_notes_id"
t.index ["user_id"], name: "index_incoming_purchases_on_user_id"
end
create_table "item_instances", options: "ENGINE=InnoDB DEFAULT CHARSET=latin1", force: :cascade do |t|
t.integer "inv_number"
t.string "serial"
t.integer "po_number"
t.date "po_date"
t.date "invoice"
t.date "date_out"
t.decimal "cost", precision: 8, scale: 2
t.string "acro"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "item_id"
t.index ["item_id"], name: "fk_rails_6ea33fd9d0"
end
add_foreign_key "incoming_purchases", "item_instances", column: "item_instances_id"
end
Oh, on the controller I tried:
params.require(:incoming_purchase).permit({ :item_instance_ids => [] }, :date_ordered, :user_id, :order_number, :vendor, :po_number, :tax, :shipping, :notes_id)
Again, I think the problem is how the relationship is set up between these two models. Thank you for any help.
I tried changing my permit params to the following:
params.require(:incoming_purchase).permit(:item_instances_id, :date_ordered, :user_id, :order_number, :vendor, :po_number, :tax, :shipping, notes_id: [], item_instances_id: [])
I was able to add an item but of course item_instances_id did not go through. When the params comes through it looks like this:
{"utf8"=>"✓", "authenticity_token"=>"d3jF73WyKCs69RSCFDvQlh7RyUAg0GQk8m7GKHX6/tt+Ve/1Y1oE5P1UtIMJfCIYS+YL0DwZth9UlDcnyW1uiA==", "incoming_purchase"=>{"item_instance_ids"=>["", "31"], "date_ordered"=>"2020-09-01", "user_id"=>"2", "order_number"=>"1", "vendor"=>"1", "po_number"=>"1", "tax"=>"1", "shipping"=>"1", "note_ids"=>[""]}, "commit"=>"Create Incoming purchase", "controller"=>"incoming_purchases", "action"=>"create"}
notice the item_instance_ids however, on the incoming_purchases model it's
item_instances_id notice the position of that s on ids and instances.
It looks like the filters you are passing into permit are not correct.
It probably needs to be note_ids: [] as this is a has_many relationship.
And when passing nested parameters into permit they should be placed at the end. So, you also have to move item_instance_ids to the end, either before or after note_ids: [].
Edit
You might be better off with a has_many :though relationship for tying items to a purchase. I'm not sure how your Item model looks like so I kept it simple.
incoming_purchase.rb
class IncomingPurchase < ApplicationRecord
has_many :purchase_items
has_many :items, through: :purchase_items
end
purchase_item.rb
class PurchaseItem < ApplicationRecord
belongs_to :incoming_purchase
belongs_to :item
end
item.rb
class Item < ApplicationRecord
has_many :purchase_items
has_many :incoming_purchases, through: :purchase_items
end
Related
I am having a trouble that I am new with ROR and want to save some images for the organization using nest attributes or for simplicity just a String in order to try the nested attributes saving in the database but actually it is not saved.
Organization Model
class Organization < ApplicationRecord
has_secure_password
has_many :needs, dependent: :destroy
has_many :org_images, dependent: :destroy
has_many :stringas, dependent: :destroy
accepts_nested_attributes_for :org_images, :reject_if => lambda { |t| t['org_image'].blank? }
accepts_nested_attributes_for :stringas, :reject_if => lambda { |t| t['stringa'].blank? }
Schema
create_table "org_images", force: :cascade do |t|
t.string "caption"
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
end
create_table "stringas", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "organization_id"
end
Organization Controller
def new
#organization = Organization.new
3.times {#organization.org_images.build}
#organization.stringas.build # added this
end
def organization_params
params.require(:organization).permit(:org_name, :email, :password, :info,:image, :website_URL, :contacts, :logo_url , :password_confirmation ,stringas_attributes:[:name,:id,:organization_id,:created_at,:updated_at] ,org_images_attributes: [:id,:organization_id,:caption, :photo_file_name, :photo_content_type,:photo_file_size,:photo_updated_at])
end
Organization Form
<div class= "field">
<% if builder.object.new_record? %>
<p>
<%= builder.label :caption, "Image Caption" %>
<%= builder.text_field :caption %>
</p>
<p>
<%= builder.label :photo, "Image File" %>
<%= builder.file_field :photo %>
</p>
<% end %>
<% if builder.object.new_record? %>
<p>
<%= builder.label :name %>
<%= builder.text_field :name%>
</p>
<% end %>
<% end %>
Stringa and org_image Models
class OrgImage < ApplicationRecord
belongs_to :organization
has_attached_file :photo, :styles => { :small => "150x150>", :large => "320x240>" }
validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes
end
class Stringa < ApplicationRecord
belongs_to :organization
end
Organization cotroller create
def create
#organization = Organization.new(organization_params)
respond_to do |format|
if #organization.save
session[:organization_id]=#organization.id
format.html { redirect_to #organization, notice: 'Organization was successfully created.' }
format.json { render :show, status: :created, location: #organization }
else
format.html { render :new }
format.json { render json: #organization.errors, status: :unprocessable_entity }
end
end
end
git repository
Thanks for your help
It seems that problem lies in unpermitted org_images attributes in your OrganizationsController. You should add this to your organization_parameters method:
params.require(:organization).permit( ... , org_images_attributes: [:photo, :caption])
EDIT:
After digging a bit deeper I found out that above solution isn't always working. There's an issue on this topic in Rails repo on GitHub. If you want to find nice workaround that'll suit your needs you should read it, or check out this answer.
I've been going at this for about 5 hours now and have tried just about everything. I'm a front-end dev with limited rails experience so I could just be 100% off base.
Here are my models:
class Apartment < ActiveRecord::Base
validates :name, :amenities, presence: true
has_many :apartment_amenities
has_many :amenities, through: :apartment_amenities
accepts_nested_attributes_for :amenities
end
class Amenity < ActiveRecord::Base
validates :name, presence: true
has_many :apartment_amenities
has_many :apartments, through: :apartment_amenities
end
class ApartmentAmenity < ActiveRecord::Base
belongs_to :apartment
belongs_to :amenity
end
schema:
create_table "amenities", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "apartment_amenities", force: :cascade do |t|
t.integer "apartment_id"
t.integer "amenity_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "apartment_amenities", ["amenity_id"], name: "index_apartment_amenities_on_amenity_id", using: :btree
add_index "apartment_amenities", ["apartment_id"], name: "index_apartment_amenities_on_apartment_id", using: :btree
create_table "apartments", force: :cascade do |t|
t.string "name"
t.string "address"
t.string "website"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Apartment controller:
class Admin::ApartmentsController < AdminController
before_action :set_apartment, only: [:edit, :update, :destroy]
def new
#apartment = Apartment.new
end
def create
#apartment = Apartment.new(apartment_params)
respond_to do |format|
if #apartment.save
format.html { redirect_to apartments_path, notice: 'Apartment was successfully created.' }
format.json { render :show, status: :created, location: #apartment }
else
format.html { render :new }
format.json { render json: #apartment.errors, status: :unprocessable_entity }
end
end
end
private
def set_apartment
#apartment = Apartment.find(params[:id])
end
def apartment_params
params.require(:apartment).permit(:name, :address, :website, amenities_attributes: [:id])
end
end
and last but not least the new apartment form
<%= form_for([:admin, #apartment]) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.collection_check_boxes(:amenities, Amenity.all, :id, :name ) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Everything looks right when I load the page up and the apartments are saved but the amenities aren't actually getting saved. Thanks for taking a look.
Its because your form fields don't match your strong params. Look at the source code of your form. I suspect you'll find that the n checkboxes look something like
apartment[amenities]
But your strong params has the amenities_attributes as a nested hash. Look at the params hash in the logs and you'll see how the form data is formatted. You'll need to change the form to use a fields_for or change the strong params
params.require(:apartment).permit(:name, :address, :website, amenities: [])
I think you need to permit the name for amenities_attributes as follows:
def apartment_params
params.require(:apartment).permit(:name, :address, :website, amenities_attributes: [:id, :name])
end
I currently have 3 models (user, pairing, meetings), and the join table meetings_pairings.
User.rb
class User < ActiveRecord::Base
enum role: [:student, :supervisor, :admin]
has_many :students, class_name: "User",
foreign_key: "supervisor_id"
belongs_to :supervisor, class_name: "User"
has_and_belongs_to_many :pairings
end
Pairings.rb
class Pairing < ActiveRecord::Base
has_and_belongs_to_many :supervisor, class_name: 'User'
belongs_to :student, class_name: 'User'
has_and_belongs_to_many :meetings, join_table: :meetings_pairings
end
Meetings.rb
class Meeting < ActiveRecord::Base
enum status: [:available, :unavailable]
has_and_belongs_to_many :pairings, join_table: :meetings_pairings
end
Schema.rb (relevant bits)
create_table "meetings", force: :cascade do |t|
t.date "meeting_date"
t.datetime "meeting_time"
t.integer "status", default: 0, null: false
t.boolean "accepted"
end
create_table "meetings_pairings", id: false, force: :cascade do |t|
t.integer "pairing_id"
t.integer "meeting_id"
end
add_index "meetings_pairings", ["meeting_id"], name: "index_meetings_pairings_on_meeting_id"
add_index "meetings_pairings", ["pairing_id"], name: "index_meetings_pairings_on_pairing_id"
create_table "pairings", force: :cascade do |t|
t.integer "supervisor_id"
t.integer "student_id"
t.string "project_title"
end
add_index "pairings", ["student_id"], name: "index_pairings_on_student_id", unique: true
add_index "pairings", ["supervisor_id"], name: "index_pairings_on_supervisor_id"
I created the view and controller to enable a user (supervisor, which is in a pairing) to create a meeting. However I don't know how to add this association to the join table.
meetings_controller.rb
class MeetingsController < ApplicationController
def index
#meetings = Meeting.all
end
def new
#meeting = Meeting.new
end
def create
#meeting = Meeting.new(meeting_params)
if #meeting.save
redirect_to meetings_path, :notice => "Meeting Created!"
else
redirect_to meetings_path, :notice => "Meeting Failed!"
end
end
def show
#meeting = Meeting.find(params[:id])
end
private
def meeting_params
params.require(:meeting).permit(:meeting_date, :meeting_time)
end
end
Form from the view
<%= form_for #meeting do |f| %>
<div class="field">
<%= f.label :meeting_date %><br />
<%= f.text_field :meeting_date %>
</div>
<div class="field">
<%= f.label :meeting_time %><br />
<%= f.time_select :meeting_time, :ampm => true, :minute_step => 30, :default => {:hour => '9', :minute => '0'} %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This creates an entry in the meetings table, so my question is how can I make it so that an entry is made into the join table with the pairing id of the current user who created the meeting ?
Decided to use a has_many :through (user-meeting-user) relationship instead. Question no longer relevant.
I am trying to figure out how to register certain values to their respective table using the form, check the order form to better understand which values need to be registering to which table.
I have also displayed the table entries, models and controller related to this question. If someone can guide me to where I can obtain further understanding on coding the associations in forms that would be great.
order form
<%= simple_form_for(#order) do |f| %>
<%= f.association :items, collection: Item.all, label_method: :name, value_method: :id %>
<%= [need to display the price of the item selected] %>
<%= f.input :quantity ???? [need to register in the order_items table] %>
<%= [register sub total to orders table] %>
<%= f.submit %>
<% end %>
tables
create_table "order_items", force: true do |t|
t.integer "item_id"
t.integer "order_id"
t.integer "quantity"
end
create_table "orders", force: true do |t|
t.integer "user_id"
t.integer "client_id"
t.boolean "status"
t.decimal "sub_total"
end
create_table "items", force: true do |t|
t.string "name"
t.decimal "price"
t.integer "stock"
end
models
class Order < ActiveRecord::Base
...
has_many :order_items
has_many :items, :through => :order_items
end
class Item < ActiveRecord::Base
...
has_many :order_items
has_many :orders, :through => :order_items
end
class OrderItem < ActiveRecord::Base
belongs_to :item
belongs_to :order
end
orders controller
def create
#order = Order.new(order_params)
#order.user_id = current_user.id
#order.status = TRUE
end
def order_params
params.require(:order).permit(:code, :client_id, :user_id, :memo, :status, item_ids: [])
end
I'm creating basic message board where many comments belong to a post and a post belongs to only one topic. My issue is that I'm not sure how create a new Topic from the Post model's form. I'm receiving an error in my Post controller:
ActiveRecord::AssociationTypeMismatch in PostsController#create
Topic(#28978980) expected, got String(#16956760)
app/controllers/posts_controller.rb:27:in `new'
app/controllers/posts_controller.rb:27:in `create'
app/controllers/posts_controller.rb:27:
#post = Post.new(params[:post])
Here are my models:
topic.rb:
class Topic < ActiveRecord::Base
has_many :posts, :dependent => :destroy
validates :name, :presence => true,
:length => { :maximum => 32 }
attr_accessible :name
end
post.rb:
class Post < ActiveRecord::Base
belongs_to :topic, :touch => true
has_many :comments, :dependent => :destroy
attr_accessible :name, :title, :content, :topic
accepts_nested_attributes_for :topics, :reject_if => lambda { |a| a[:name].blank? }
end
comment.rb:
class Comment < ActiveRecord::Base
attr_accessible :name, :comment
belongs_to :post, :touch => true
end
I have a form:
<%= simple_form_for #post do |f| %>
<h1>Create a Post</h1>
<%= f.input :name %>
<%= f.input :title %>
<%= f.input :content %>
<%= f.input :topic %>
<%= f.button :submit, "Post" %>
<% end %>
And it's controller action: (posts create)
def create
#post = Post.new(params[:post]) # line 27
respond_to do |format|
if #post.save
format.html { redirect_to(#post, :notice => 'Post was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
In all of the examples I find, tags belong to posts. What I'm looking for is different and probably easier. I want a post to belong to a single tag, a Topic. How can I create a Topic through the Post controller? Can someone point me in the right direction? Thank you very much for reading my question, I really appreciate it.
I'm using Rails 3.0.7 and Ruby 1.9.2. Oh and here's my schema just in case:
create_table "comments", :force => true do |t|
t.string "name"
t.text "content"
t.integer "post_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "posts", :force => true do |t|
t.string "name"
t.string "title"
t.text "content"
t.integer "topic_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "topics", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
Thanks again.
You should have:
accepts_nested_attributes_for :topic
on Post rather than the other way around.
#post = Post.new(params[:topic]) in my controller fixed the error.