안녕하세요 저는 게시물이 belongs_to 인 사용자와 사용자 has_many 게시물이있는 게시물 모델이 있습니다. 사용자 이름 검색 사용자 이름
<td><%= post.user_id %></td>
내가이 잘 작동 포스트를 만드는 사용자 ID를 얻을 :
포스트 테이블은 내가 가진 내 공연 게시물에 순간에 USER_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
실제로 웹 서비스 API를 지불하는 클라이언트가 없다면 format.json 행을 꺼내십시오. 튜토리얼을위한 것입니다. 실제 프로젝트에 과도한 추측 코드가 있어서는 안됩니다 – Phlip