我有两个模型,用户和治疗(您可以将其视为一条消息)。
用户:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_many :sent_treatings, :foreign_key => "requestor_id", :class_name => "Treating", dependent: :destroy
has_many :received_treatings, :foreign_key => "requestee_id", :class_name => "Treating", dependent: :destroy
end
治疗:
class Treating < ActiveRecord::Base
attr_accessible :intro, :proposed_date, :proposed_location
validates :intro, presence: true, length: { maximum: 190 }
validates :requestor_id, presence: true
validates :requestee_id, presence: true
belongs_to :requestor, class_name: "User"
belongs_to :requestee, class_name: "User"
default_scope order: 'treatings.created_at DESC'
end
我在处理控制器设置'被请求者'时遇到了麻烦:
class TreatingsController < ApplicationController
before_filter :signed_in_user
def create
requestee = ?
requestor = current_user
@received_treating = requestee.received_treatings.build(params[:treating])
@received_treating.requestor = requestor
if @received_treating.save
flash[:success] = "Treating request sent!"
redirect_to users_path
else
render 'static_pages/home'
end
end
end
问题我试图替换为:User.find(params [:id]),希望找到当前'users / show'视图中的用户,但是我收到此错误:
找不到没有ID的用户
我也试过User.find(params [:treating] [:requestee_id]),但这也没用。有任何想法吗?
谢谢!
编辑:
views / shared / _treating_form.html.erb(这引用了用户控制器中的@received_treating,show action):
<div class="field">
<%= f.text_area :intro, placeholder: "Write your introduction here..." %>
</div>
<%= f.submit "Send", class: "btn btn-large btn-primary" %>
编辑:添加其他用户个人资料页面:
<% provide(:title, @user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>
<%= gravatar_for @user %>
<%= @user.name %>
</h1>
</section>
<% if signed_in? %>
<section>
<%= render 'shared/treating_form' %>
</section>
<% end %>
</aside>
<div class="span8">
<% if @user.received_treatings.any? %>
<h3>Treating requests (<%= @user.received_treatings.count %> received)</h3>
<ol class="treatings">
<%= render @received_treatings %>
</ol>
<%= will_paginate @received_treatings %>
<% end %>
</div>
</div>
答案 0 :(得分:0)
我认为只需在hidden_field中添加@user.id
即可。
<%= f.hidden_field :requestee_id, :input_html => { :value => @user.id }
<div class="field">
<%= f.text_area :intro, placeholder: "Write your introduction here..." %>
</div>
<%= f.submit "Send", class: "btn btn-large btn-primary" %>
您还可以填充字段
<%= form_for @user.received_treatings.build do %>
<%= f.hidden_field :requestee_id %>
....
在控制器上只需
@received_treating = current_user.sent_treatings.build params[:treating]
我怀疑这是否有效,但我认为它可以帮助你。