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.
Related
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
I am creating a self referential relationship for services. The idea is to allow you to add a potentially infinite level of sub services to a service, so services can have children, and those children can have children, etc.
To do this I have crated two classes, Services, and SubServices. SubServices is a simple join table with a parent_service_id and a child_service_id. I am able to create everything in the rails console and it works just fine. Both the child and parent associations work. It's just in the controller that it's breaking down
schema:
create_table "services", force: :cascade do |t|
t.string "name"
t.integer "business_category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["business_category_id"], name: "index_services_on_business_category_id", using: :btree
end
create_table "sub_services", force: :cascade do |t|
t.integer "child_service_id"
t.integer "parent_service_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["child_service_id"], name: "index_sub_services_on_child_service_id", using: :btree
t.index ["parent_service_id"], name: "index_sub_services_on_parent_service_id", using: :btree
end
models:
class SubService < ApplicationRecord
belongs_to :parent_service, class_name: 'Service'
belongs_to :child_service, class_name: 'Service'
end
class Service < ApplicationRecord
belongs_to :business_category
has_many :client_services # TODO REMOVE
has_many :clients, :through => :client_services # TODO REMOVE
has_many :business_services
has_many :businesses, :through => :business_services
has_many :parental_services, foreign_key: :parent_service_id, class_name: "SubService"
has_many :child_services, through: :parental_services
has_many :children_services, foreign_key: :child_service_id, class_name: "SubService"
has_many :parent_services, through: :children_services
validates :name, presence: true
validates :name, uniqueness: { scope: :business_category, message: "service already added" }
end
SubService new action:
def new
#sub_service = #service.child_services.new
respond_to do |format|
format.html
format.js { render :new }
end
end
SubService create action:
def create
#sub_service = #service.child_services.new(service_params);
# binding.pry
if #sub_service.save
redirect_to(admin_business_categories_path)
end
end
service_params:
def service_params
params.require(:sub_service).permit(:name)
end
Sub Service new view:
<%= render 'form', f: f %>
<% end %>
_form:
<div class="col-12 col-md-10">
<div class="col-12 col-md-12">
<%= f.input :name, label: 'Service Name' %>
</div>
</div>
<div class="col-12 col-md-2">
<div class="btn-group-vertical" role="group" aria-label="...">
<button id="serviceFormCancelButton" class="btn btn-danger">CANCEL</button>
<%= f.submit 'SAVE', class: 'btn btn-success' %>
<br>
</div>
</div>
This is the error my console is returning
ActiveModel::UnknownAttributeError (unknown attribute 'parent_service_id' for Service.):
app/controllers/admin/sub_services_controller.rb:14:in `create'
Rendering C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (3.0ms)
Rendering C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)
Rendering C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.0ms)
Rendered C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/actionpack-5.0.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (846.1ms)
You want a Service > SubService and then potentially Service > SubService > SubService > SubService.... right? You're getting the unkown attribute error because parent_id is on SubService. You can do what you want with just the Service model. Just put the parent_id on that.
You could then get rid of the SubService model.
class Service
belongs_to :parent_service, foreign_key: :parent_id, class_name: 'Service'
has_many :child_services, class_name: 'Service'
end
I'm new to Rails and trying to create an C2C marketplace App just to understand how rails works and start some real project later on.
The idea is that User can place Order to other User. Orders is related with user's Printer (you choice user where you want to print on /order page). Printer in its turn have many colors to print
For now, Im stack with very basic things.
I want to display list of all printers with owner's name and colors available on /order page in Orders controller. Thank you in advance for any ideas how I can do this
class User < ActiveRecord::Base
has_many :printers, dependent: :destroy
has_many :orders, dependent: :destroy
end
class Order < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
end
class Printer < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :model, presence: true, allow_nil: true
has_many :materials, dependent: :destroy
end
Orders controller with index action (/orders)
class OrdersController < ApplicationController
def index
#printers = Printer.all
end
end
And index.html.erb
<% #printers.each do |p| %>
<div class="col-xs-9">
<div><%= "USERNAME HERE" %></div> <!--Do not know how to display parent's model here? -->
<div><%= p.model %></div> <!--Works fine-->
<div><%= p.colors.each do |c| c.color end %></div> <!--Display array instead of strings-->
</div>
<div class="col-xs-3">
<button>Order</button>
</div>
<% end %>
Simplified schema.db
ActiveRecord::Schema.define(version: 20160627132435) do
create_table "colors", force: :cascade do |t|
t.string "color"
t.integer "printer_id"
end
create_table "orders", force: :cascade do |t|
t.string "price"
t.string "status"
t.integer "user_id"
end
create_table "printers", force: :cascade do |t|
t.string "model"
t.integer "user_id"
end
add_index "printers", ["user_id"], name: "index_printers_on_user_id", using: :btree
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
end
add_foreign_key "orders", "users"
add_foreign_key "printers", "users"
end
I think you should be able to do:
<% #printers.each do |p| %>
<div class="col-xs-9">
<div><%= p.user.first_name %></div> <!--Do not know how to display parent's model here? -->
<div><%= p.model %></div> <!--Works fine-->
<div><% p.colors.each do |c|
<%= c.color %>
<% end %></div> <!--Display array instead of strings-->
</div>
<div class="col-xs-3">
<button>Order</button>
</div>
<% end %>
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 am now trying to show the images, which a user already registered, on his or her 'mypage'.
Then, I wrote some codes as below.But it doesn't work.Could you give me some advises?
☆members_controller
#member= Member.find(params[:id])
#member.groups.reverse.map do |group|
#join_groups_images = group.imageurl
☆(members)show.html.erb
<div class="join_groups_images">
<%= image_tag #join_groups_images, :width => '20px' ,:height => '25px' %>
</div>
☆(model)member.rb
class Member < ActiveRecord::Base
attr_accessible :admin, :mail, :memo, :name, :pass, :user, :pass_confirmation
has_many :group_in_members, :dependent => :destroy
has_many :groups, :through => :group_in_members
☆(model)group_in_member.rb
class GroupInMember < ActiveRecord::Base
attr_accessible :group_id, :member_id
belongs_to :group
belongs_to :member
end
☆schema.rb
create_table "groups", :force => true do |t|
t.string "name"
t.text "memo"
t.boolean "admin"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "imageurl"
end
You didn't provide whole code from action in members controller, but I assume, that you are using .map{|| } in wrong way. You need a variable with array or even method in Member model.
class Member < ActiveRecord::Base
...
def images
groups.reverse.map(&:imageurl)
end
...
end
and then, put this in your view
<ul class="join_groups_images">
<% #member.images.each do |image| >
<li><%= image_tag image %></li>
<% end>
</div>
that should do the trick.