'Encountered NoMethodError in one to many relationship
I am making a prototype of a chat room system. Specifically, users can create a "room" first, and then add "messages" from the room. However, when I increment the message I get a NoMethodError with the message undefined method `room' for #<Message:0x00007fcaa80530a0>, where it goes wrong is <%= form_with(model: [ @message.room, @message ]) do |form| %>. I'm not sure what I'm missing or writing wrong.
This is the View (new.html.erb)
<h1>New Message</h1>
<%= form_with(model: [ @message.room, @message ]) do |form| %>
<div class = "field">
<%= form.text_field :content %>
<%= form.submit "Send" %>
</div>
<% end%>
<%= link_to 'Back', @message.room %>
This is the MessagesController
class MessagesController < ApplicationController
before_action :set_room, only: [:new, :create]
def new
@message = @room.messages.new
end
def create
@message = @room.messages.create!(message_params)
respond_to do |format|
format.html {redirect_to @room}
end
end
private
def set_room
@room = Room.find(params[:room_id])
end
def message_params
params.require(:message).permit(:content)
end
end
The RoomsController was created by Scaffold.
This is model Message
class Message < ApplicationRecord
belongs_to :message
end
This is the model Room
class Room < ApplicationRecord
has_many :messages
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
