rails object expected got string in Rails 3 - ruby-on-rails-3

class Result < ActiveRecord::Base
has_one :p1, :class_name => "Player", :foreign_key => 'player_id', :validate => true
end
When i try to create a new record by using Result.new it throws Result(#203425120) expected, got String(#127815260).
I seen most of the related questions..But they given only select sql based. Not creating new records.. Any comments would be appreciated..

Probably you have p1_id in the database instead of just p1.
So, When you are referring to players, you should use the
<%= f.collection_select :p1_id, Player.all, :id, :name %>
Referred from:
rails object expected got string

Related

activeadmin habtm better example for uniqueness case

Am able to manage habtm as per follow, and I wanted a better way for this
I have habtm between User and Tag on Rails 3, aa 0.5.1
Tag name is uniq
f.input :tags, :label => 'Assign existing tag'
# this above allows to select from existing tags, but cannot allow to create one
f.has_many :tags, :label => 'Add new tags, modify existings' do |ff|
ff.input :name
ff.input :_destroy, :as => :boolean
end
# this above allows to create new one but not allow to specify existing one
# if we specify existing one, uniqueness wont let create this one, neither existing get used
# and throws validation error
any hints?
Adding my models
class User < ActiveRecord::Base
has_and_belongs_to_many :tags
scope :tagged_with, lambda {|tags| joins(:tags).where("tags.name" => tags)}
accepts_nested_attributes_for :tags, :allow_destroy => true
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :users
validates :name, :uniqueness => { :case_sensitive => false }
end
Try this,
f.label => 'Assign existing tag'
f.select :tags, Tag.all.map{|t| [t.tag_name, t.id]}, {:prompt => "Select Tag name" }
this above allows to select from existing tags, don't have option to create one
For the Second thing add this line in the model,
validates :tags, :uniqueness => {:scope => :tag_name}
here the :tag_name is your name of the fieldname. This throw an error if the tag name already exists when you create a duplicate.
It's just an idea as per your question. This won't be your exact answer because your specification is not enough to give you the exact answer.

Supplying data for a form re-population from a different model

so I have a tricky issue here I'm not sure how to solve.
I have a Provider model that has_many :educational_affiliations
EducationalAffiliation belongs_to :institution & belongs_to
:provider
I have about 9000 universities in my database, so I'm using the handy-dandy rails3-jquery-autocomplete gem to give me type-ahead support. That's all working great - on TOP of that I'm using cocoon to support the nesting of the :educational_affiliations form inside of the provider's edit form.
So here's where the issue comes — This works great for submitting new affiliation records, (I'm using some jquery to set the :institution_id on the :educational_affiliations_attributes object, works great)
BUT when I return to edit this later, of course the :institution_name isn't populated, because it's not part of the :educational_affiliations model, it's in the :institution model.
Here's what I just tried in my :educational_affiliations, which I assume is the right solution:
class EducationalAffiliation < ActiveRecord::Base
attr_accessible :degree, :graduation_year, :honors, :institution_name, :institution_id, :provider_id
belongs_to :institution
belongs_to :provider
# attr_accessor :institution_name
validates :institution_id, :graduation_year, :provider_id, :degree, presence: true
def institution_name
Institution.find(institution_id).name
end
end
(i had it working for saving using the attr_accessor, but I've commented it out for now)
So when I render the edit view with the above, I get a ActiveRecord::RecordNotFound: Couldn't find Institution without an ID error — but when I open a debugger on that statement, the model DOES seem to know the institution_id...so confused why it doesn't pick it up.
Am I just doing this in the worst way possible? I assume there's a dumb solution.. :)
Here's the partial that needs the name populated:
.nested-fields
= f.input :institution_name, url: autocomplete_institution_name_data_path, as: :autocomplete, :input_html => {:id_element => '#provider_educational_affiliations_institution_id'}
= f.input :institution_id, as: :hidden
= f.input :provider_id, as: :hidden, input_html: { value: current_provider.id }
= link_to_remove_association "Remove Degree", f
Instead of the virtual attribute method, try the following to define the attribute:
delegate :name, :name=, :to => :institute, :prefix => true

Rails: Uniqueness of two attributes in join table causing 500 error

I have the following models, which basically are trying to mean that a professor has knowledge of many subjects for a particular level. The subjects are fixed, so there will be no new subjects created, there will be just "related" to a professor through the knowledge join table.
class Subject < ActiveRecord::Base
# Self Associations
has_many :subcategories, :class_name => "Subject"
belongs_to :category, :class_name => "Subject",:foreign_key => "parent_id"
# Associations
has_many :knowledges
has_many :professors, :through => :knowledges
end
class Professor < ActiveRecord::Base
# Associations
has_many :knowledges
has_many :subjects, :through => :knowledges
...
end
class Knowledge < ActiveRecord::Base
# Associations
belongs_to :professor
belongs_to :subject
has_one :level
attr_accessible :subject_id, :professor_id
validates :subject_id, :uniqueness => { :scope => :professor_id }
end
I want to have a form that will let a professor to add a subject to his account, and I decided to have a form for a knowledge (as I want to be able to insert a level too).
It looks like this:
<%= simple_form_for #knowledge,:url => professor_knowledges_path, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group select optional">
<%= label_tag "Subject Type", nil, :class => "select optional control-label"%>
<div class="controls">
<%= select_tag "Parent Subject", options_from_collection_for_select(#parent_subjects, "id", "name"), :id => "knowledge_parent_subject" %>
</div>
</div>
<%= f.input :subject_id, :collection => #subjects, :label => "Subject" %>
<%= f.input :level %>
<%= f.button :submit, t('add_form'),:class => 'btn-primary' %>
<% end %>
And in the create action of the Knowledges controller I have this:
def create
#knowledge = Knowledge.create(:professor_id => current_professor.id, :subject_id => params[:knowledge][:subject_id])
end
I would like/expect to get an ActiveRecord saying that this knowledge can't be inserted because there is a uniqueness violation, but nops, I just see a 500 in the logs and a rollback, but it seems the execution goes on. So my question is: What am I doing wrong, or how I could improve this modeling situation? I believe the form needs to be related to the join model as I want to have fields of that model on it...But maybe I am wrong, and I could do in an easy/cleaner way.
EDIT:
As asked in one of the comments, here is the log of the submission of the form and the 500 error right after the rollback:
Started POST "/professors/1/knowledges" for 127.0.0.1 at 2012-07-01 00:45:39 -0700
Processing by KnowledgesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4JVyxWnIh37kyBwLwLGTHk/znsI1c5wrJvaWjKKT5tM=", "Parent Subject"=>"1", "knowledge"=>{"subject_id"=>"1"}, "commit"=>"Añadir", "professor_id"=>"1"}
Professor Load (0.4ms) SELECT `professors`.* FROM `professors` WHERE `professors`.`id` = 1 LIMIT 1
Completed 500 Internal Server Error in 4ms
I added some conditions in the create action, like this:
def create
#knowledge = Knowledge.new(:professor_id => current_professor.id, :subject_id => params[:knowledge][:subject_id])
if #knowledge.save
flash[:notice] = "Success..."
redirect_to professor_path(current_professor)
else
render :action => 'new'
end
end
And this actually shows the following right after the 500:
Completed 500 Internal Server Error in 6ms
ActiveRecord::RecordInvalid (Validation failed: Subject has already been taken):
I wonder why the exception is raised instead of just adding the errors into the object and let me manage that situation. Isn't what the following line should be doing?
validates :subject_id, :uniqueness => { :scope => :professor_id }
That error means you are trying to insert duplicate subject_id / professor_id pairs on that table. Most often happens when either the subject_id or professor_id is null.
Are you sure the controller is getting the correct parameters? I would check the logs to make sure the inserts are what you would expect.
I don't have enough reputation to comment...my answer is more some things to try than a definitive answer, sorry.
It looks like the save is failing due to validation errors. You can try to handle those in your 'else' block. The following will give you a description of all validation errors (useful for debugging).
#knowledge.errors.full_messages
You haven't shown what is happening in the 'new' action. I suspect this is where the errors are occurring.
Does the same issue occur (i.e. the validation problem) in the console? If so, try cleaning out your databases (beware - the following will erase & rebuild all your databases).
rake db:drop:all db:create:all db:migrate db:test:prepare
Also, if you haven't already, add an index to your migration for Knowledge to prevent duplicates being added to the db. e.g.
add_index :knowledges, [ :professor_id, :subject_id ], unique: true

has_many association with conditions on ActiveRecord

I have this models: Store and Address.
The second model Address I'm using this with other models and has some custom fields inside for different models.
Yes like polymorphic but without the varchar field for Class, I'm using an integer. (optimization stuff)
now on my Store model the association in set like this:
class Store < ActiveRecord::Base
has_many :addresses, :foreign_key => "parent_id", :conditions => ['parent_kind = ?', 2]
accepts_nested_attributes_for :addresses
end
Now in my controller I do:
#store.addresses.build
And I can use f.fields_for :addresses... inside the form.
The problem comes out when I submit the form and the data is saved to the database.
The record in the stores table is saved, the record in addresses is saved with the parent_id of the store in place, but the parent_kind is in 0 which is the default value for that attribute on MySQL.
My Quick fix was this:
#store = Store.new(params[:store])
#store.addresses[0].parent_kind = 2
if #store.save
....
But I know there must be another way.
Anny suggestions?
Thanks.
Did you try using a hidden field in your nested form?
<%= f.fields_for :addresses, Address.new do |ff| %>
<%= ff.hidden_field :parent_kind, :value => 2 %>
...
EDIT
If you don't want to use it due to security concerns, here's another way that might help. You can try using an association callback like so:
class Store < ActiveRecord::Base
has_many :addresses, :foreign_key => "parent_id",
:conditions => ['parent_kind = ?', 2],
:before_add => Proc.new { |store,address| address.parent_kind = 2}
accepts_nested_attributes_for :addresses
end

mongoid save embedded documents

I'm trying to build up on the following tutorial from railscast:
http://railscasts.com/episodes/196-nested-model-form-part-1
I'm trying to make everything work with mongodb and mongoid.
the scenario is:
I want to creates events linked to a location. Each events (dance class) contains many lessons.
So I thought that an embedded relationship would be perfect.
Here are my models
model Lesson
class Lesson
include Mongoid::Document
include Mongoid::Slug
field :name, :type => String
embedded_in :event
slug :name
end
model Event
class Event
include Mongoid::Document
include Mongoid::Slug
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
field :name, :type => String
field :description, :type => String
field :date, :type => DateTime
validates_presence_of :name
has_one :venue
referenced_in :venue
embeds_many :lessons
slug :name
end
model Venue
class Venue
include Mongoid::Document
include Mongoid::Slug
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
field :name, :type => String
field :location, :type => String
validates_presence_of :name, :location
belongs_to :event
slug :name
end
event controller
def create
#event = Event.new(params[:event])
if #event.save
flash[:notice] = 'Event was successfully created.'
end
respond_with(#Event, :location => events_url)
end
def update
# #event = Event.find(params[:id])
#event = Event.find_by_slug(params[:id])
if #event.update_attributes(params[:event])
flash[:notice] = "Event was succesfully updated"
end
respond_with(#event)
end
Then I have my Event view where I can create events and link it to a Venue. But I'd like to be abe to create the lessons from the Event view/model.
so I used the fields_for to generate a field linked to the Lessons model.
= form_for #event do |f|
.field
= f.label :name
%br/
= f.text_field :name
.field
= f.label :description
%br/
= f.text_area :description
.field
= f.label :venue_id
%br/
= f.collection_select :venue_id, Venue.all, :id, :name
.field
= f.label :date
%br/
= f.datetime_select :date
%h3 Add a Class
= f.fields_for :lessons do |builder|
= render "lesson_fields", :f => builder
.actions
= f.submit 'Save'
When I create or edit a new event I get an error message:
undefined method `extract_id' for "test":String
But the request parameter message on the error page shows my lessons value in the Event document.
"lessons"=>{"name"=>"test name lesson"}
When I remove the fields_for line, everything works fine. But then i don't know how to save the value for the nested documents.
I have same problem with embeds_many, but when i try change to has_many. It works!. Maybe you can try too.
can you post the exact code you use to create the Event, including parameters?
which version of Mongoid and Rails are you using?
First thing I noticed is that the following parameter hash does not match your Lessons model:
"lessons"=>{"content"=>"test name lesson"} # this looks wrong
this should be:
"lessons"=>{"name" => "test name lesson"}
Looks like your lessons form has the wrong label for the text input field .. it should be :name , not :content
To dry things up, you might want to try if the 'nested_form' gem works for you:
after installing the gem, use the nested_form_for instead of form_for in your view.
Check here for a more detailed description:
How can I handle this type of multi level forms in rails
See:
https://github.com/ryanb/nested_form (it's also referenced in the RailsCast you mentioned)
You also might want to check this:
field_for and nested form with mongoid
The conclusion of this story is...
I removed everything related to mongoid_slug and it started to work.
I then put everything back as it was to try to find out how to make it work with mongoid_slug and it just worked, like out of the box.
:(
Please include the following code in model event.rb
**accepts_nested_attributes_for :lessons**
This will fix your problem