Strange undefined method model_name issue - ruby-on-rails

I want to edit my record in the database with nested attributes. In my controller I have:
def edit
#chocolate = Chocolate.new.kinds.find_by_id(params[:chocolate_id])
end
and in my edit.html.erb I have:
form_for #chocolate do |choco|
but it gives me the next error:
undefined method model_name issue
I cannot understand why it gives me such error. Any options?

Those methods aren't really made to be mixed together in that way.
I'm guessing that you're trying to do something like this instead:
#chocolate = Chocolate.includes(:kinds).find(params[:chocolate_id])
Then you are querying the database for the Chocolate and associated Kind records instead of trying to instantiate a new record.

Related

should bookmark.id return nil

hey guys so i'm having issues adding a Like/Dislike function to my bookmarks on my page.
basically i have a snippet of code given to me that lives in my User model:
def liked(bookmark)
likes.where(bookmark_id: bookmark.id).first
end
however when i am running the server and clicking on the topic to show the associated bookmarks, i keep getting the
undefined method `id' for nil:NilClass
my question is... firstly what is going wrong here? and secondly, whats the difference between bookmark_id and bookmark.id?
im pretty sure id doesn't exist for bookmark... and if not... how would i add it?
ive tried via migration, unfortunately nothing great came from that
use this code:
def liked(bookmark)
likes.where(bookmark_id: bookmark.id).first if bookmark.present?
end
You are getting id for nil:NilClass error due to object is not present.i.e bookmark object is nil.
bookmark_id is the field name for the bookmark class.And bookmark.id returns the id of the bookmark object, only if the object is present.
bookmark.id raises an exception.
Ensure bookmark instance is passed to the liked method and is not nil
You need to ensure that your bookmark argument is not nil.
You could try the following code
def liked(bookmark)
likes.where(bookmark_id: bookmark.try(:id)).first
end
or an even better version
def liked(bookmark)
likes.find_by(bookmark_id: bookmark.try(:id))
end
Above code will return a nil object or first like
To answer your second question, bookmark_id is an column name here for your Like model whereas bookmark.id is a method call on bookmark object.
You can try the following.
def liked(bookmark)
likes.where(bookmark_id: bookmark.id).try(:first) unless bookmark.blank?
end

how to tell if an association changed in a rails edit form

I'm using simple_form_for to create/update two models that are related by using f.association. But whenever I update it, I need to somehow get a collection of what changed in the association. It is a has_and_belongs_to_many relationship between a model called ProjectLevels and a model called PackageContents. So in the project_levels_controller in the strong params I have package_content_ids: []. But if I try to use #project_level.package_content_ids_changed? it gives an undefined method error, even though #project_level.name_changed? will work. I also tried #project_level.package_contents.changed?and it also gives a no method error. So how can I see which package_contents were added or deleted from a project_level in an edit form?
You can compare array from params in your controller:
new_ids = params[:package_content_ids]
with current model's ids (before you assign params to it):
old_ids = #project_level.package_contents_ids
You can just use standard Ruby array methods to gain information you need:
old_ids - new_ids # what was deleted
new_ids - old_ids # what was added
new_ids & old_ids # what was not changed
new_ids.sort == old_ids.sort # if something was changed

Undefined method update when updating a record in Rails

I'm having trouble parsing through a hash and then saving certain parts to my database. I'm able to iterate through it to get to the information that I need. My problem is updating the record in my database. I'm trying to update an existing record in my database based on if the country code for each country matches the country code in the XML parse.
In my controller I have:
class CountriesController < ApplicationController
def index
#countries = Country.all
travel_alerts = request_data('http://travel.state.gov/_res/rss/TAs.xml')
travel_warnings = request_data('http://travel.state.gov/_res/rss/TWs.xml')
# Sets warnings
warnings_array = travel_warnings["rss"]["channel"]["item"]
warnings_array.each do |warning|
#country = Country.find_by(code: warning["identifier"].strip)
#country.update(title: warning["title"],
description: warning["description"])
end
end
end
...
I've tried using .update and .save, but neither works. When I try update I get:
undefined method `update' for nil:NilClass
Does the update method need to be explicitly defined in the Country model? If so, what's the best way to have access to the parsed information since that's being done in the controller?
It raises an error, because Country by given code was not found, then find_by returns nil, on which update method does not exist.
Instead of find_by executrun find_by! - you should get ActiveRecord::RecordNotFound error
If it is expected some countries do not exist put your update statement within if block
if #country
#country.update ...
end

undefined method `attribute_method_matcher' for nil:NilClass

I'm getting this error "undefined method `attribute_method_matcher' for nil:NilClass".
My controller name is Cad Its function is
def index
#cadempty = Cad.new
#caddata = Cad.all
end
The error is on creating the new object. If I comment Cad.new the code works fine.
Earlier I thought it could be because I have a method named 'new' and I was Using User.new to create a blank object for the form. But its not the error I renamed the method to something else and the error still exists. I have no idea what I'm doing wrong.
Maybe one of your column names in the database table is a reserved word.
Avoid using names for methods that are reserved words in the language.

Rails 3 undefined method `create' for nil:NilClass error while trying create a related object

I have two models, User and Profile, in one-to-one relation and I am trying to create a new profile for a user if it does not exist yet:
user = User.includes(:profile).find( params[:user_id] )
unless user.profile.present?
user.profile.create
end
But I am getting an error: undefined method `create' for nil:NilClass
Well, two things. Firstly, I assume the code is wrong, as that only enters the block if the profile is there (and hence can't create it).
if user.profile.blank?
user.profile.create
end
looks like more correct code.
Secondly, when you use a has_one, you don't use .create like you do with has_many. This is because the relation object is directly returned, and not a "proxy" method like a has_many. The equivalent method is create_profile (or create_x where x is the object)
Hence, try the following code:
if user.profile.blank?
user.create_profile
end

Resources