enter code hereon rails 7 and ruby version 3.2.0
my method returns nil even though it got data.
i am following a tutorial to build an app.
in my bookings view new.html.erb has
<% if #booking_type.payment_required? %>
and the bookings controller
def new
#booking = Booking.new
#booking_type = BookingType.find_by(name: params[:booking_type])
end
def booking_params
params.require(:booking).permit(:booking_type_id, :status, :name, :email, :start_at, :end_at, :notes)
end
Booking_types Controller params
def booking_type_params
params.require(:booking_type).permit(:name, :location, :description, :color, :duration, :payment_required, :price, :user_id)
end
After creating a the booking_type instance in the bookings controller
#booking_type = BookingType.find_by(name: params[:booking_type])
for the payment_required method in view, i still get undefined method `payment_required?' for nil:NilClass
In the method:
def new
#booking = Booking.new
#booking_type = BookingType.find_by(name: params[:booking_type])
end
It's expected to receive a booking_type parameter. If the parameter is not set or there is no BookingType record with that name, the #booking_type variable will be nil, resulting in the undefined method payment_required?' for nil:NilClass` error.
Related
I am able to create a new instance of my Team class successfully, but whenever I call save on the instance I get:
undefined method `title' for #<Team:0x00007fddfc7fb570>
This is in my "team_attributes=" method, so it is running off of strong params, which does not include a :title method or attribute.
def created_user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :privilege,
position_attributes: [
:title,
:description,
:team_id,
],
:team_attributes => [
:name,
:description,
:id,
:profile #for determining if the form came from the profile page. Do not allow into update or create method for team
]
).with_defaults(user_id: current_user.id)
end
And here is my "team_attributes=" method:
def team_attributes=(team_attributes)
self.update(user_id: self.id) if self.user_id.nil?
binding.pry
# selecting a team from a dropbox
if !team_attributes[:id].nil?
#team = Team.find_by(id: team_attributes[:id])
# updating an existing team
elsif self.position && team_attributes[:name]!="" && team_attributes[:profile].nil?
self.team.update(team_attributes.with_defaults(company: self.company, user_id: self.user_id))
#team = self.team
else
# creating a team from the profile page
if team_attributes[:profile] == "profile"
#team = Team.create(name: team_attributes[:name], description: team_attributes[:description], company: self.creator.company, user_id: self.user_id )
# creating a team
elsif team_attributes[:name] != ''
#team = Team.new(team_attributes.except(:profile).with_defaults(company: self.company, user_id: self.user_id))
#team.save
else
end
end
self.update(assigned_position_id: #position.id) if self.position
if #position
#position.update(team_id: #team.id) if #team
end
end
This is where the instance is being created
# creating a team from the profile page
if team_attributes[:profile] == "profile"
#team = Team.create(name: team_attributes[:name], description: team_attributes[:description], company: self.creator.company, user_id: self.user_id )
I am not sure where the error is coming from. You can see from the params and method there is no "title" attribute. Running "new" creates a new instance fine, but saving it through "save" or "create" raises the error above. Any help would be appreciated. Thanks.
I keep getting error "undefined method `model_name' for nil:NilClass" when I try to create a new record of my model UserLanguage that has two foreign keys: language and user.
the language_id of the new UserLangauge object is nil after form submit.
user_languages#new view
<%= simple_form_for(#user_language) do |f| %>
<%= f.association :language, label_method: :name, value_method: :id, include_blank: false, include_hidden: false %>
<%= f.input :proficiency, collection: #proficiencies, include_blank: false, include_hidden: false %>
<%= f.submit "Add Language"%>
<% end %>
user_languages controller
def new
#user_language = UserLanguage.new
...
end
def create
user_language = UserLanguage.new(user_language_params)
user_language.user = current_user
if user_language.save
redirect_to my_account_path
else
render :new
end
end
private
def user_language_params
params.require(:user_language).permit(:language, :proficiency, :seeking, :sharing)
end
I assign user with current_user (devise), but am unable to get the language to associate with the new user_langauge record....
I even tried manually assigning #user_language.language_id = params[:language] from the from data right before saving the object, but then the langauge_id is just assigned 0 for unknown reason.
The problem is that you are assigning user_language = ... in your create method. This assigns a local variable instead of an instance variable. A local variable is only available in that lexical scope (the create method in this case) while Rails exposes the controllers instance variables to the view.
You can rewrite this method to:
def create
#user_language = current_user.user_languages
.new(user_language_params)
if #user_language.save
redirect_to my_account_path
else
render :new
end
end
This assumes that you have setup a has_many :user_languages relation in your User class.
I am trying to use multiple permits in a single method similar to the following (psuedocode)
def index
model.create(
params.permit(:b, :c)
)
params.permit(:a)
end
This is my actual code
def create
params.permit(:create_special_categories)
balance_sheet = ::BalanceSheet.create!(
balance_sheet_params.merge(date: Time.zone.now.to_date, entity: #entity)
)
balance_sheet.create_special_categories if params[:create_special_categories]
render json: balance_sheet, serializer: ::Api::V3::BalanceSheetSerializer
end
def balance_sheet_params
params.permit(
:id,
:entity,
:entity_id,
:date,
:name
)
end
However, I get the following error...
ActionController::UnpermittedParameters:
found unpermitted parameter: :create_special_categories
UPDATE
my solution was to avoid strong parameters all together.
def create
balance_sheet = ::BalanceSheet.new(
date: Time.zone.now.to_date, entity: #entity
)
balance_sheet.name = params[:name]
balance_sheet.save!
balance_sheet.create_special_categories if params[:create_special_categories]
render json: balance_sheet, serializer: ::Api::V3::BalanceSheetSerializer
end
This line doesn't have any effect, params.permit are not chained or added to a previous permit, you must use the result, that is why it's almost always used in a separate method.
params.permit(:create_special_categories)
What you must do is use what that returns for your following statements
permitted_params = params.permit(:create_special_categories)
Model.create(permitted_params)
...however you really should outsource this to a special method like you already have. You will have to tweak this to your use-case obviously.
def balance_sheet_params
if params[:create_special_categories]
params.permit(:id,
:entity,
:entity_id,
:date,
:name,
:create_special_categories)
else
params.permit(
:id,
:entity,
:entity_id,
:date,
:name)
end
end
I have a modified copy of https://github.com/talho/openphin/blob/master/app/controllers/admin/invitations_controller.rb
The main code is primarily the same, however our system was upgraded a few months back to Rails 4.x and the invitation system no longer works.
The method with the issue is create. I have tried swapping out:
#invitation = Invitation.new(params[:invitation])
with
#invitation = Invitation.create(invitation_params)
And creating
def invitation_params
params.require(:invitation).permit!
end
However, here is what I have:
invitation_params = {"name":"Test","subject":"test","body":"test","organization_id":"","author_id":24448}
#invitation = {"id":null,"name":null,"body":null,"organization_id":null,"author_id":null,"subject":null,"created_at":null,"updated_at":null,"lock_version":0}
Also, if I use create!, then my output error is:
E, [2015-12-14T13:03:38.664099 #24385] ERROR -- : Validation failed: Author can't be blank (ActiveRecord::RecordInvalid)
I could use any guidance/help on why everything ends up as null.
You call return what leaved the method, before you call save! in the record. Furthermore you might want to read about Strong Parameters. You might want to change your code to:
#invitation = Invitation.new(
params.require(:invitation).permit(
:name, :subject, :body, :organization_id, :author_id
)
)
#invitation.save!
render :json => { :invitation => #invitation }.as_json
return
Please note that you usually do not need to call return in controller method. And when you call save! immediately after new then create! might be an better option:
def create
invitation = Invitation.create!(invitation_params)
render json: { invitation: invitation }.as_json
end
private
def invitation_params
params.require(:invitation).permit(
:name, :subject, :body, :organization_id, :author_id
)
end
im following ryan bates screen cast on how http://railscasts.com/episodes/219-active-model on how to validate a form without a database
but i keep getting an undefined method valid?
heres my controller
def create
#contacts = FreshDeskApiWrapper.new().post_tickets(params[:contacts])
if #contacts.valid?
redirect_to new_contact_path
else
flash[:notice] = "OOps"
render action: 'new'
end
end
I can seem to call
$ FreshDeskApiWrapper.new().valid?
just fine in the console but it does not seem to like it when i tack on the
$ FreshDeskApiWrapper.new().post_tickets(params[email: 'user#example.com']).valid?
i get an undefined method valid?
There is something im not understanding about this
heres my fresh_desk_api_wrapper.rb file i created in my models folder
class FreshDeskApiWrapper
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :config, :client, :subject, :email, :custom_field_phone_number_50754, :custom_field_company_50754, :description
validates :subject, presence: true
validates :email, presence: true
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\#([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
self.config = YAML.load_file("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
self.client = Freshdesk.new(config[:url], config[:api_key], config[:password])
end
def post_tickets(params)
client.post_tickets(params)
end
def persisted?
false
end
end
post_tickets is something im defining in there
You can call valid? on an single instance of an object, not multiple. #contacts would imply that your post_tickets method is returning multiple objects.
try something like this:
#contacts = FreshDeskApiWrapper.new(post_tickets(params[:contacts])
what seems to be the problem is that the method you are adding dosnt return a active record object, so the method valid? is not available
Edit:
maybe this:
#contacts = FreshDeskApiWrapper.new(FreshDeskApiWrapper.post_tickets(params[:contacts])
omg im so dumb so what i did was
def create
#contacts = FreshDeskApiWrapper.new(params[:contacts])
#contacts.post_tickets(params[:contacts])
if #contacts.valid?
redirect_to new_contact_path
else
flash[:notice] = "OOps"
render action: 'new'
end
end
and it works!
Im still struggling to learn all this.....thanks for your guy's guidance it really helped