Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4-- User expected, got string

I have a simple messaging system built into my rails app.

The table looks like this:

create_table :messages do |t|
  t.integer :from_id
  t.integer :to_id
  t.string :subject
  t.text :message

  t.timestamps
end

The model is simple as well:

belongs_to :to_id, class_name: "User", :foreign_key => "to_id"
belongs_to :from_id, class_name: "User", :foreign_key => "from_id"

When I submit the message form however, I am getting a type mismatch, and when I try to create a new message in the rails console, it throws the same error.

User(#-588576898) expected, got String(#-603326958)

Apparently it is expecting a User object rather than simply the user.id value. I assume this is due to an error in how I created the model?

Where did I go wrong?

EDIT:

The form code is below. However, note that I am experiencing the same issue when creating a Message directly from the Rails console, so I am assuming it's the model:

> m = Message.new
=> #<Message id: nil, from_id: nil, to_id: nil, subject: nil, message: nil, created_at: nil, updated_at: nil>
> m.from_id = 1
ActiveRecord::AssociationTypeMismatch: User(#-582821898) expected, got Fixnum(#-597136528)

Here's the form, stripping the labels and HTML:

<%= form_for @message, :url => {:controller => "messages", :action => "create"}, :html => {:class => 'form-horizontal form', :role => 'form'} do |f| %>
<%= f.select :to_id, options_from_collection_for_select(User.all, :id, :first_name) %>
<%= f.text_field :subject %>
<%= f.text_area :message %>
<%= f.submit class: "btn btn-large btn-primary" %>
<% end %>
like image 796
user101289 Avatar asked Sep 25 '26 21:09

user101289


2 Answers

The name of the association (the first argument to belongs_to) should not be the same as the name of the column that contains the foreign key.

For example

belongs_to :to, class_name: "Message"

As it currently stands the accessor methods generated for the association are shadowing the accessor method for the attribute.

like image 107
Frederick Cheung Avatar answered Sep 27 '26 13:09

Frederick Cheung


Try to give other names to your relations, maybe to_user and from_user . Then you can use these names when creating message.

like image 40
zauzaj Avatar answered Sep 27 '26 14:09

zauzaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!