Rails 4,img_tag作为form_for控件?

时间:2015-04-13 17:15:48

标签: ruby-on-rails

我正在尝试构建一个表单,用户可以为其用户个人资料选择头像图像。我有一个名为avatars的表(其中包含id(INT)和url(字符串),另有一个名为users(带有一堆东西和img(INT))。

我想创建所有头像图像的预览,然后让用户点击他想要选择的图像(最好这会突出显示图像边框),然后将头像ID写入用户表在img。我认为我已经建立了适当的关联,但现在我已经找到了如何处理img_tag上的点击事件的问题。这是否是正确的方法,如果不是,我应该怎么做?

到目前为止我的观点:

<div class="col-lg-6">  
    <%= form_for @user do |f| %>
        <%if @user.errors.any? %>
            <% for message in @user.errors.full_messages %>
            <div class="alert alert-danger"><%= message %></div>
            <% end %>
        <% end %>
        <%= f.label :username %>
        <%= f.text_field :username, class:'form-control', placeholder:'MightyWizard5578' %><br />
        <%= f.label :email %>
        <%= f.text_field :email, class:'form-control', placeholder:'example@topdeckandwreck.com' %><br /> 

</div>

<div class="col-lg-12">
    <strong>Pick your avatar:</strong><br />    
    <% @avatars.each do |avatar| %>
    <%= image_tag(avatar.url, height: '75', width: '75') %>
    <% end %>
</div><br />

<div class="col-lg-6">
    <%= f.label :bio %>
    <%= f.text_area :bio, class:'form-control', placeholder:'Tell us a bit about yourself!' %><br /> 
</div>
    <% end %>

我的控制员:

class UsersController < ApplicationController

  ... 

  def edit
    @avatars = Avatar.all
    @user = current_user
  end

  def update
  end

  def user_params
    params.require(:user).permit(:username, :email, :password, :password_confirmation, :img, :bio, :auth_token)    
  end
end

应用程序控制器:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  helper_method :current_user

  private
    def current_user
        @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
    end
end

协会

class User < ActiveRecord::Base
    belongs_to :avatar
end

class Avatar < ActiveRecord::Base
    has_many :users
end

1 个答案:

答案 0 :(得分:0)

这是在rails中完成的:

<div class="col-lg-12">
    <strong>Pick your avatar:</strong><br />    
    <% @avatars.each do |avatar| %>
        <label>
             <%= f.radio_button :avatar, avatar.id %>
             <%= image_tag(avatar.url, height: '75', width: '75') %>
        </label>
    <% end %>
</div>

所以你可以从列表中选择头像。其他所有内容(如隐藏单选按钮,突出显示边框等)都是在CSS

中完成的