您好我有一个职位模型,其中职位belongs_to用户和用户has_many职位。从用户ID检索用户名
的职位表有一个user_id的
此刻在我的节目的帖子,我有:
<td><%= post.user_id %></td>
我得到的用户ID谁做这工作正常后。当用户表包含列User_name时,我如何获取用户名?是否需要向用户添加post_id或?
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :username, :password_confirmation, :remember_me
has_one :profile
has_many :orders
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
attr_accessible :content, :title, :user_id
validates :title, presence: true,
length: { minimum: 5 }
end
在我的职位控制器我有
def create
@post = Post.new(params[:post])
@post.user_id = current_user.id
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render json: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
如果你没有客户端实际上为web服务api付费,那么把这些format.json行出去。他们只是用于教程;真正的项目不应该有过多的投机代码 – Phlip