#ruby-on-rails #ruby-on-rails-4 #has-many-through #grouped-collection-select
#ruby-on-rails #ruby-on-rails-4 #имеет много сквозных #сгруппированный-коллекция-выбор
Вопрос:
У меня небольшая проблема с ассоциацией корыта has_many. У меня есть 3 модели User, Tag, Taggings. Здесь код:
Модель пользователей:
class User < ActiveRecord::Base
#---------------------------------Associations---------------------------------------
attr_accessor :login
has_many :taggings
has_many :tags, through: :taggings
has_one :profile, :dependent => :destroy , autosave: true
accepts_nested_attributes_for :profile
#---------------------------------End Association------------------------------------
#---------------------------------Tagging ----------------------------------------------
def self.tagged_with(name)
Tag.find_by_name!(name).users
end
def self.tag_counts
Tag.select("tags.*, count(taggings.tag_id) as count").
joins(:taggings).group("taggings.tag_id")
end
def tag_list
tags.map(amp;:name).join(", ")
end
def tag_list=(names)
self.tags = names.split(",").map do |n|
Tag.where(name: n.strip).first_or_create!
end
end
#---------------------------------End Tagging --------------------------------------------
end
Теги модель:
class Tag < ActiveRecord::Base
has_many :taggings
has_many :users , through: :taggings
validates :name , presence: true
end
Модель тегов:
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :user
end
Проблема в том, что я хочу добавить collection_select в моем представлении регистрации / редактирования. Но я понятия не имею, как я могу сделать это самостоятельно. Я потратил много времени, чтобы получить рабочее решение. В любом случае, я был бы очень рад и рад, если бы кто-нибудь мог мне помочь. Я включаю только соответствующий код.
Еще раз вот мое мнение:
<div class="form-group">
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-lg-3 control-label">Rechtsgebiete:</label>
<div class="col-lg-8">
<%= f.collection_select :tag_list, Tag.order(:name), :id, :name, {}, {multiple: true, class: 'form-control'} %>
</div>
</div>
</div>
Контроллер регистрации:
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters, if: :devise_controller?
after_filter :send_welcome_mail, only: :create
def update #TODO fix the avatar uploade
if params[:user].present?
new_params = params.require(:user).permit(:username, :email, :password, :password_confirmation, :current_password, :admin, :approved, :tag_list, profile_attributes: [:anrede, :titel, :vorname, :nachname, :user_id, :kanzlei, :kanlei_nr, :straße, :straße_nr, :plz, :stadt, :land, :telefon, :avatar, :avatar_cache])
change_password = true
if params[:user][:password].blank?
params[:user].delete("password")
params[:user].delete("password_confirmation")
new_params = params.require(:user).permit(:username, :email, :admin, :approved, :tag_list, profile_attributes: [:anrede, :titel, :vorname, :nachname, :user_id, :kanzlei, :kanlei_nr, :straße, :straße_nr, :plz, :stadt, :land, :telefon, :avatar, :avatar_cache])
change_password = false
end
@user = User.find(current_user.id)
is_valid = false
if change_password
is_valid = @user.update_with_password(new_params)
else
is_valid = @user.update_without_password(new_params)
end
if is_valid
set_flash_message :notice, :updated
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end
end
end
protected
def send_welcome_mail
if @user.save
UserMailer.welcome_email(@user).deliver
end
end
end
И запрос:
Processing by Users::RegistrationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"G7lzhNmFyRBd3aSxQmmqGQG6IwAFywSdjPBoMFFIwYY=", "user"=>{"profile_attributes"=>{"id"=>"83", "anrede"=>"Herr", "titel"=>"", "vorname"=>"Furkan", "nachname"=>"Adigüzel", "kanzlei"=>"cnjw", "kanlei_nr"=>"njewin", "straße"=>"Korallusring", "straße_nr"=>"5", "plz"=>"21109", "stadt"=>"Hamburg", "land"=>"Deutschland", "telefon"=>"21374891207"}, "username"=>"Furkan", "tag_list"=>["", "1", "2"], "email"=>"Furkan_adiguezel@hotmail.de", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}, "commit"=>"Update"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 20 ORDER BY "users"."id" ASC LIMIT 1
Unpermitted parameters: id
Unpermitted parameters: tag_list
Unpermitted parameters: id
Unpermitted parameters: tag_list, current_password
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 20]]
(0.1ms) begin transaction
Profile Load (0.1ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = ? LIMIT 1 [["user_id", 20]]
SQL (0.4ms) DELETE FROM "profiles" WHERE "profiles"."id" = ? [["id", 83]]
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE (LOWER("users"."username") = LOWER('Furkan') AND "users"."id" != 20) LIMIT 1
SQL (0.2ms) INSERT INTO "profiles" ("anrede", "created_at", "kanlei_nr", "kanzlei", "land", "nachname", "plz", "stadt", "straße", "straße_nr", "telefon", "titel", "updated_at", "user_id", "vorname") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [["anrede", "Herr"], ["created_at", "2014-06-14 14:39:30.626720"], ["kanlei_nr", "njewin"], ["kanzlei", "cnjw"], ["land", "Deutschland"], ["nachname", "Adigüzel"], ["plz", "21109"], ["stadt", "Hamburg"], ["straße", "Korallusring"], ["straße_nr", "5"], ["telefon", "21374891207"], ["titel", ""], ["updated_at", "2014-06-14 14:39:30.626720"], ["user_id", 20], ["vorname", "Furkan"]]
(1.8ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 68ms (ActiveRecord: 3.1ms)
Started GET "/" for 127.0.0.1 at 2014-06-14 16:39:30 0200
Processing by VisitorsController#index as HTML
(0.2ms) SELECT COUNT(*) FROM "users"
Rendered visitors/index.html.erb within layouts/application (2.5ms)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 20 ORDER BY "users"."id" ASC LIMIT 1
Profile Load (0.2ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = ? LIMIT 1 [["user_id", 20]]
Rendered layouts/_navigation_links.html.erb (7.0ms)
Rendered layouts/_navigation.html.erb (8.1ms)
Rendered layouts/_messages.html.erb (0.1ms)
Completed 200 OK in 42ms (Views: 41.2ms | ActiveRecord: 0.6ms)
Комментарии:
1. Вы получаете какую-либо ошибку?
2. да, неопределенный метод `map’ для:id:Symbol
3. Разве это поле
taggings_id
не должно быть простоtag_id
?4. не получил ту же ошибку. Я считаю, что это проблема с:id
5. А также опубликуйте соответствующий код контроллера.