i have the following Problem:
I have three different data models : customer , periods and request. A request consist of the customer_id and the periods_id (i dont know why its periodS_id because i genereated a scaffold called period). Now if i want to create a request i want to choose a customer and a period so my code in the form.html.erb of requests is:
<div class="field">
<%= f.label 'Kunde auswählen' %><br />
<%= f.collection_select :customer_id, Customer.all, :id, :name %>
</div>
<div class="field">
<%= f.label 'Zeitfenster auswählen' %><br />
<%= f.collection_select :periods_id, Period.all , :id, :description %>
</div>
and this works pretty well. I can choose the name of the customers and peridos but then if i want to create a request i get the error message undefinded method, because he cant display the name of periods in the show.html.erb:
<%= #request.customer.name%>
<%= #request.periods.name%>
My idea is a mistake in the datamodels. I´m not sure if this mxn relationship works. Here the datamodels:
class Request < ActiveRecord::Base
validates :periods_id, :customer_id, presence: true
belongs_to :customer
belongs_to :period
end
class Period < ActiveRecord::Base
has_many :requests, :dependent => :destroy
has_many :customers, :through => :requests
end
class Customer < ActiveRecord::Base
has_many :requests, :dependent => :destroy
has_many :periods, :through => :requests
end
and it works for customer: if i delete period.name he can show the name of the specific customer.
Any ideas ?
Its give error of period because request model belongs to period, not request has_many period
<%= #request.period.name%>
Change .periods to .period
Related
This is a new error to me, and struggling to resolve it. It also states: Roaster(#70130698993440) expected, got "1" which is an instance of String(#70130675908140)
It's highlighting my create method in my Roasts Controller:
def create
#roast = Roast.new(roast_params)
The scenario is that I'm trying to create a triple nested form. for three models Roasts Countries and Regions where roasts has many countries and countries has many regions.
I'm assuming there is something wrong with the roast params, but I can see what it is. I have added the associations there for the nested models
def roast_params
params.require(:roast).permit(:roaster, :name, :bestfor, :beans, :roast, :tastingnotes, :notes, :slug, :avatar, :countries_attributes => [:country_name, :regions_attributes => [:region_name]])
end
my form
<div class="form-group">
<%= form.fields_for :countries do |countries_form| %>
<%= countries_form.label :country %>
<%= countries_form.text_field :name, class: "form-control" %>
</div>
<div class="form-group">
<%= form.fields_for :regions do |regions_form| %>
<%= regions_form.label :region %>
<%= regions_form.text_field :region_name, class: "form-control" %>
<% end %>
<% end %>
</div>
Roast Controller
...
def new
#roast = Roast.new
#roast.countries.build.regions.build
end
...
roast model
class Roast < ApplicationRecord
has_many :tastings
has_many :countries
has_many :notes, through: :tastings
has_many :comments, as: :commentable
belongs_to :roaster
accepts_nested_attributes_for :countries
country model
class Country < ApplicationRecord
has_many :regions, inverse_of: :country
accepts_nested_attributes_for :regions
belongs_to :roasts
region model
class Region < ApplicationRecord
belongs_to :country
I've nested the regions params in the country params, is that correct? I also saw on SO other issues with suggestions for setting config.cache_classes to true in development.rb but that didn't help here.
Update
So looking at this further, I believe it's not related to the nested forms, but rather a collection_select I'm using.
<%= form.label :roaster, class: 'control-label' %>
<%= form.collection_select(:roaster, Roaster.order(:roaster_name).all, :id, :roaster_name, prompt: true, class: "form-control") %>
So this select is pulling the roaster_name from a model called Roaster.
My params now look like the below:
params.require(:roast).permit(:roaster_name, :roaster, :name, :bestfor, :beans, :roast, :tastingnotes, :notes, :slug, :avatar, :countries_attributes => [:country_id, :country_name, :regions_attributes => [:region_id, :region_name]])
And looking at the console when submitting the form, it seems that just the :id of Roaster is getting passed, rather than the value of :roaster_name.
{"utf8"=>"✓",
"authenticity_token"=>"EG+zty85IiVsgipm1pjSAEZ7M66ELWefLq8Znux+cf89sSnVXxielRr1IaSS9+cJvdQD8g1D4+v2KqtKEwh6gw==",
"roast"=>{"roaster"=>"1", "name"=>"Espress", "countries_attributes"=>{"0"=>{"country_name"=>"UK"}}, "regions"=>{"region_name"=>"Highlands"}, "bestfor"=>"", "roast"=>"", "tastingnotes"=>""},
"commit"=>"Create Roast"}
Can't work this out
ActiveRecord::AssociationTypeMismatch is raised when an association-setter (Roast#roaster= in this case) is called with a value that is not an instance of the expected class. Roaster was expected, got String.
The issue seems to be with passing roaster in as a param, which is "1" (String) in your example. I'm guessing this is actually an ID of a Roaster, the form code in the question does not show it.
Perhaps you meant to permit and pass a roaster_id param?
def roast_params
params.require(:roast).permit(:roaster_id, # ...
end
I'm quite new to rails and I have some problem with views...I have among others these three models : reservation,route and stop.
When you make a reservation, you have to select the route and the city of departure/arrival.
EDIT
class Route < ActiveRecord::Base
has_many :stops, :dependent => :destroy
has_many :reservations, :dependent => :destroy
belongs_to :train
end.
class Stop < ActiveRecord::Base
belongs_to :route
has_many :reservation_deps, class_name: "Reservation", foreign_key: "dep_city_id"
has_many :reservation_arrs, class_name: "Reservation", foreign_key: "arr_city_id"
end
class Reservation < ActiveRecord::Base
belongs_to :user
belongs_to :route
belongs_to :arr_city, class_name: "Stop",foreign_key: "arr_city_id"
belongs_to :dep_city, class_name: "Stop",foreign_key: "dep_city_id"
end
I don't know if it is possible but I'd like to be able to select my city of departure/arrival only among those that belong to the route I've chosen. Any ideas how to do that?
Thank you!
Below there's a part of my reservation's form:
<div class="field">
<%= f.label :route %><br>
<%= f.collection_select(:route_id,Route.all,:id,:as_field) %><br>
</div>
<div class="field">
<%= f.label :departure_city %><br>
<%= f.collection_select(:dep_city_id,Stop.all,:id,:city) %><br>
</div>
<div class="field">
<%= f.label :arrival_city %><br>
<%= f.collection_select(:arr_city_id,Stop.all,:id,:city) %><br>
</div>
Your stops should be linked to your routes through a has_and_belongs_to or has_many :through relationship right, since routes can contain many stops, and stops can belong to many routes. So assuming you have a route loaded on your reservations page, you should be able to just do the following
<%= f.collection_select :dep_city_id, #route.stops.all, :id, :name %>
<%= f.collection_select :arr_city_id, #route.stops.all, :id, :name %>
Alternatively something like
Edit: This will work even if the route to stops relationship is one to many.
<%= f.collection_select :dep_city_id, Stop.for_route(params[:route_id]), :id, :name %>
Edit 2:
In this case, it is expected that you have added a for_route scope to your Stop model which would just be a
scope for_route -> (route_id) { where(:route_id => params[:route_id]) }
In the basic case, you would have a page with your routes, you pick a route (link or something), and are taken to a page where you can make a reservation. The first page would have something like this
<% #routes.each do |route| %>
<%= link_to route.name, new_reservation_path(:route_id => route.id) %>
<% end %>
The links generated by the code above should link to something like /reservation?route_id=XXX
When the reservations_controller#new is run, you know what the route ID is, so you can load it with something like #route = Route.find(params[:route_id])
Then, when rendering the page you will be able to use the f.collection_select helper I specified in the first example code.
In the last case, where you dont know what route the user will pick until they have selected one on the reservations page, it gets more complicated, and you will have to start using JS to query get a list of stops a route every time a new route is chosen.
I am new to Ruby and am learning OTJ. I have been grinding on this problem for days and have read lots of other posts regarding the has_many :through pattern.
I am using RubyMine 5.4 and ruby-1.9.3-p194 with MySQL
I have three models and I need to be able to add, remove and edit the nested relationships:
The idea is that any user can have many groups of business competitors. A group (with the same group_id) has one target competitor and it's competition. Each competitor is a BizEntity with it's associated attributes. Each competitor can be a member of many different competitive groups.
I am trying to get the many to many working so I can select a user and then view/edit the users groups and related competitors.
I have run RubyMine's Inspect Code... on the models and it is clean. Yet, the Rails Model Dependency Diagram indicates (red line with ?'s at both ends) that there is an issue with the Users to BizEntity relationship.
Any assistance would be greatly appreciated.
Thanks!
Models are as follows:
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :password_digest
validates_uniqueness_of :email
has_many :competitive_insightses, :class_name => 'CompetitiveInsights'
has_many :biz_entitieses, :through => :competitive_insightses, :class_name => 'CompetitiveInsights', :source => :biz_entities
end
class CompetitiveInsights < ActiveRecord::Base
attr_accessible :biz_entity_id, :user_id, :group_id, :position, :target
belongs_to :user
belongs_to :biz_entities
end
class BizEntities < ActiveRecord::Base
attr_accessible :name, :ticker
accepts_nested_attributes_for :users
has_many :competitive_insightses, :class_name => 'CompetitiveInsights'
has_many :users, :through => :competitive_insightses, :class_name => 'CompetitiveInsights'
end
In my Controller the two commented lines cause the same type of errors
"undefined method `biz_entitieses' for nil:NilClass"
class CompetitiveInsightsController < ApplicationController
def index
#my_companies = CompetitiveInsights.find_all_by_user_id(current_user)
#competitive_insights = current_user.competitive_insightses
#biz_entitieses = current_user.biz_entitieses
if (#my_companies.nil?)
#my_companies = CompetitiveInsights.new(current_user)
#my_companies.save!
end
end
end
The edit.html.erb is not yet able to edit the biz_entity fields and throws the following error:
"undefined method `competitive_insight_competitive_insight_path' for #<#:0x007fc1fae4efd0>"
<%= form_for #my_companies do |f| %>
<div class="field">
<%= f.label :group_id %><br />
<%= f.text_field :group_id %>
</div>
<%= f.fields_for :biz_entities do |biz_entity| %>
<div class="field">
<%= biz_entity.label :ticker %><br />
<%= biz_entity.text_field :ticker %>
</div>
<% end %>
<div class="actions"><%= f.submit %></div>
<% end %>
I have two models, Artist and User that are connected through a third model, ArtistMembership.
From the edit/new Artist form, I want to be able to edit the role of any User in an existing ArtistMembership relationship for that Artist, delete ArtistMemberships, and add new AtistMembership relationships, which would include a User and :role.
Here's my Artist model:
class Artist < ActiveRecord::Base
has_many :artist_memberships, foreign_key: "artist_id", dependent: :destroy
attr_accessible :bio, :created_at, :email, :location, :name, :updated_at, :website, :pic
accepts_nested_attributes_for :artist_memberships, :allow_destroy => :true
...
end
Here's my User model:
class User < ActiveRecord::Base
...
has_many :artist_memberships, foreign_key: "user_id"
...
end
Here's my ArtistMembership model:
class ArtistMembership < ActiveRecord::Base
belongs_to :artist, class_name: "Artist"
belongs_to :user, class_name: "User"
attr_accessible :artist_id, :created_at, :role, :user_id
end
If I have a _form.hml.erb too, for editing Artists that starts:
<%= form_for #artist do |artist_form| %>
<div class="field">
<%= artist_form.label :name %>
<%= artist_form.text_field :name %>
</div>
..
<div class="actions">
<%= artist_form.submit %>
</div>
<% end %>
how can I create the related ArtistMembership forms for the aforementioned functionality?
May be this is helpful for you, see this field_for
you can use accepts_nested_attributes_for(*attr_names)
Maybe you are looking for this method.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
Refer to the "One-to-many" section.
But if I were you, I would rather use the "Nested Resource" technic.
http://guides.rubyonrails.org/routing.html#nested-resources
I'm stuck -
I'm building an accounting app in rails, and have a model where a customer will have multiple invoices as well as multiple payments (related to those invoices)
Here's a quick look at a simplified model:
class Customer < ActiveRecord::Base
has_many :customer_payments
has_many :invoices
accepts_nested_attributes_for :customer_payments, :allow_destroy => true
end
class CustomerPayment < ActiveRecord::Base
has_many :customer_payment_items
belongs_to :customer
belongs_to :invoice
accepts_nested_attributes_for :customer_payment_items
end
class CustomerPaymentItem < ActiveRecord::Base
belongs_to :invoice, :inverse_of => :customer_payment_items
belongs_to :customer_payment
end
class Invoice < ActiveRecord::Base
has_many :invoice_lines, :dependent => :destroy
has_many :customer_payment_items, :inverse_of => :invoice
belongs_to :customer
accepts_nested_attributes_for :invoice_lines, :allow_destroy => true
end
I have a nested form where I want to show Customer attributes, CustomerPayment attributes and CustomerPaymentItem attributes - which all works fine.
I also want to show Invoice attributes for each CustomerPaymentItem (each CustomerPaymentItem relates back to a single invoice) and while I can get a form to show the CustomerPaymentItem info, I can't get it to show Invoice information which is needed to give reference to the user. - I'm having trouble getting data from a belongs_to association to show on the form.
I'm at a loss - Shouldn't I be able to traverse the belongs_to association? FYI - I can send data to the log where I know the invoice data is populated during the CustomerPayment.new call, it seems to just get lost between the controller and the form.
How should I access that data? Here's the form info -- (coming from a couple of rendered forms) the stuff that doesn't show is in between the ---.
<p>
<%= f.label :amount %><br />
<%= f.text_field :amount %>
</p>
<p>
<%= f.label :invoice_id %><br />
<%= f.text_field :invoice_id %>
</p>
<p>
<% f.fields_for :invoice do |builder| %>
--- doesn't show
Invoice Detail
<p>
<%= builder.label :number %><br />
<%= builder.text_field :number %>
</p>
<p>
<%= builder.label :sub_total %><br />
<%= builder.text_field :sub_total %>
</p>
--- doesn't show
<% end %>
</p>
Am I missing something in my fields_for to show the :invoice reference data? Is my model too complex for rails to make sense of?
#corroded was right - the issue was my lack of an = sign in
<% f.fields_for :invoice do |builder| %>
I guess everyone needs to learn that lesson