我正在尝试创建一个消息模型,其中消息属于两个用户,即发件人和收件人。同样,用户将具有__ Message消息作为Sent_Messages和Received_Messages。
当我尝试创建新电子邮件时,我遇到了麻烦。我的表单很好,但是当我尝试保存时,我得到了不同的错误(取决于我最近尝试过的解决方案的尝试“用户期望,得到字符串”)。
我的模型和相关控制器defs如下:
User.rb
class User < ActiveRecord::Base
has_many :sent_messages, :class_name => "Message", :foreign_key => 'sender_id'
has_many :received_messages, :class_name => "Message", :foreign_key => 'recipient_id'
...
end
Message.rb
class Message < ActiveRecord::Base
belongs_to :sender, :class_name => 'User'
belongs_to :recipient, :class_name => 'User'
...
end
Message_Controller.rb before_filter:get_user
...
def new
@message = @user.sent_messages.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @message }
end
end
def create
@message = Message.new(params[:message])
respond_to do |format|
if @message.save
format.html { redirect_to @message, notice: 'Message was successfully created.' }
format.json { render json: @message, status: :created, location: @message }
else
format.html { render action: "new" }
format.json { render json: @message.errors, status: :unprocessable_entity }
end
end
end
...
private
def get_user
@user = User.find(params[:user_id])
end
我认识到我的尝试方式存在根本性的错误,但我对rails很新,所有相关的问题(如this和this)似乎都没有有任何答案可以帮助我。
编辑
_form:
<%= form_for([@user, @message]) do |f| %>
...
<div class="field">
<%= f.label :recipient %><br />
<%= f.text_field :recipient %>
</div>
<div class="field">
<%= f.label :subject %><br />
<%= f.text_field :subject %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>