私はこの2つのモデルがあるシンプルなアプリに取り組んでいます:
class Report < ActiveRecord::Base
attr_accessible :comments, :user_attributes
belongs_to :user
accepts_nested_attributes_for :user
end
class User < ActiveRecord::Base
attr_accessible :username
has_many :reports
end
このHAMLの新しいレポートビューもあります。
= form_for @report do |f|
.field
= f.fields_for :user do |u|
= u.label :username
= u.text_field :username
.field
= f.label :comments
= f.text_area :comments
.action
= f.submit "Submit report"
フォームは次のJSONパラメーターを送信します。
{ user_attributes => { :username => "superuser" }, :comments => "Sample comment 1." }
また、シンプルなレポートコントローラーがレコードレポートとユーザーの作成を処理します。
def create
@report = Report.new(params[:report])
@report.save
end
これにより、レポートとユーザーが同時に正常に作成されます。同じユーザー名(スーパーユーザー)で別のレポートを送信した場合、別のユーザーが作成されないようにする必要があります。Railsモデルまたはコントローラーでこれを行う簡単な方法はありますか?ありがとうございました。