2011-12-11 2 views
3

나는 이것에 잘못된 접근을하고 웹상에서 최선의 접근법을 찾으려고했지만 지금까지는 행운이 없다고 생각한다.형태의 추가 변수 - 레일

많은 메시지와 사용자가있는 프로젝트 모델이 있습니다. 메시지는 프로젝트와 사용자 모두에 속합니다 (아래에 표시된 것처럼). 그래서 프로젝트 ID와 사용자 ID를 모두 메시지 양식에 전달해야합니다. 나는 이것이 꽤 직설적이어야한다는 것을 알고 있지만, 분명히 그것을 엉망으로 만든다. 이 단계에서는 반드시 http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-hidden_field_tag을 사용하는 것이 가장 좋습니다.

도움이 될 것입니다.

프로젝트 모델 :

class Project < ActiveRecord::Base 
    belongs_to :user 
    has_many :users 
    has_many :messages, :dependent => :destroy 
end 

사용자 모델 :

class User < ActiveRecord::Base 
attr_accessor :password 
attr_accessible :first_name, :last_name, :username, :email, :password, :password_confirmation 

has_many :projects 
belongs_to :projects 
has_many :messages 
end 

메시지 모델 :

class Message < ActiveRecord::Base 
    attr_accessible :title, :message 
    belongs_to :project 
    validates :title, :presence => true 
    validates :message, :presence => true 
end 

프로젝트 쇼 :

def show 
    @project = Project.find(params[:id]) 
    @title = @project.title 
    @curent_user = current_user 
    @message = Message.new  
    begin 
     @messages = @project.messages 
    rescue ActiveRecord::RecordNotFound  
    end 
    end 

/shared/_message.html.erb

<%= form_for @message do |f| %> 
<%= f.label :title %>: 
<%= f.text_field :title %><br> 

<%= f.label :message %> 
<%= f.text_area :message %> 

<%= f.submit %> 

    <% end %> 

메시지 만이 전달 그래서 나는 필드에서에 USER_ID/PROJECT_ID를 전송하는 방법을 식별하기 위해 노력하고, 당신의 시간을 행동

def create 
    @message = @project.messages.build(params[:message]) 
    if @message.save 
    flash[:success] = "Message created!" 
    redirect_to root_path 
    else 
    render 'pages/home' 
    end 
end 

감사 생성 메시지 작성시.

답변

1

양식을 제출할 때 최종 사용자가 수정할 수 없도록 컨트롤러에서 project_id/user_id를 설정하십시오.

메시지 컨트롤러 작성 작업에서 @ project.messages.build를 사용하면 project_id가 자동으로 설정됩니다. 그런 다음 @ message.user = @current_user로 사용자를 설정할 수 있습니다.